In Java, one can write something like this:
Scanner scan = new Scanner(System.in);
x = scan.nextInt();
y = scan.nextDouble();
etc.
What is the equivalent of this in Python 3? The input is a list of space separated integers and I do not want to use the strip() method.
Use the input() method:
x = int(input())
y = float(input())
If you're looking to take a list of space separated integers, and store them separately:
`input: 1 2 3 4`
ints = [int(x) for x in input().split()]
print(ints)
[1, 2, 3, 4]
After you get your input using "input" function you could do :
my_input = input("Enter your input:")
# my_input = "1, 2"
def generate_inputs(my_input):
yield from (i for i in my_input.split())
inputs = generate_inputs(my_input)
x = int(next(inputs))
y = int(next(inputs)) # you could also cast to float if you want
If you want less code :
scan = (int(i) for i in input().split())
x = next(scan)
y = next(scan)
Related
This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed last year.
I am creating a translator in python . This translator is going to change a normal text to a text with some special things :
At the first of each word we add "S"
At the End of each word we add "Di"
We reverse each word
example :
Hello Everyone --> SHello SEveryone --> SHelloDi SEveryoneDi --> iDolleHS iDenoyrevES
I did first two parts easily; but third part is a little tricky
my code :
n = input("Enter Text : ")
y = n.split()
z = 0
for i in y:
x = str("S" + i)
y[z] = x
z = z + 1
z = 0
for i in y:
x = str(i + "Di")
y[z] = x
z = z + 1
print(y)
z = 1
for i in y:
globals()["x%s" % z] = []
for j in i:
pass
In pass part I wanna to do something like this x{i}.append(j)
and then we reverse it.
How do I do this?
You can reverse it using ::-1, it means from start to beginning in reverse order:
For example:
print("abcd"[::-1]) # will prin dcba
So the code for every word can look like this:
result = "S"+word+"Di"
result = result[::-1]
Now you just have to put that in a loop and do it for every word.
I'm trying to store this single input:
5 2 100
2
8
1
3
into three variables (N, x, n) and a list object
the variables are correctly written, being N = 5, x = 2, n = 100
N, x, n = input().split(' ')
list = [input()]
I've tried using this, but the list only intakes the ['2'], while I need it to be ['2', '8', '1', '3']
I've also tried using while and if loops to try to iterate through the input,
but that didn't seem to work for me.
To enter the list you use this approach:
N, x, n = input().split(' ')
lst = []
while True:
el = input()
if len(el) > 0:
lst.append(el)
else:
break
Note that you'll have a list of strings, and also N, x and n are strings - so will need to take care of it...
Ok, first of all, I'm a total newb in python.
So, what I'm trying to achieve is creating a list of lists, in which first element is a string and second is an integer.
First, I enter a number of sets and then every set on a new line, so it looks like this:
3
Alex 40
Boris 30
Claire 50
This seems to be working
n = int(input())
nums = []
for i in range(n):
num = input().split()
num[1] = int(num[1])
nums.append(num)
But I've been trying to improve this method:
n = int(input())
nums = []
for i in range(n):
nums.append([[x, int(y)] for x, y in input().split()])
Which in return gives me "ValueError: too many values to unpack (expected 2)"
That's what input().split() is doing under-the-hood:
input().split()
"Boris 30".split()
["Boris", "30"]
Every time you iterate over ["Boris", "30"], it'll yield first "Boris" and then "30". So when you do
[... for x, y in input().split()]
What you're actually doing is:
[... for x, y in ["Boris", "30"]]
At first it may look it's doing the right thing, but it's trying to unpack the string "Boris" into x and y (thus the "too many values to unpack" error: it expected only 2 values, but it received 5). Note that if "Boris" was replaced with "Bo", the code would not raise this specific error (but it still wouldn't do what you're expecting).
You can fix this by unpacking the input().split() itself:
n = int(input())
nums = []
for i in range(n):
x, y = input().split()
nums.append([x, int(y)])
Split the user input into a list, and remove the unnecessary list comprehension. Also, provide meaningful messages to the user:
n = int(input('enter the number of lines: '))
nums = []
for i in range(n):
lst = input('enter name and age: ').split()
nums.append([lst[0], int(lst[1])])
print(nums)
I'm new to Python and I was wondering if anyone could help explain how to code the following task in Python using stdin
Programming challenge description:
You have 2 lists of positive integers. Write a program which multiplies corresponding elements in these lists.
Input:
Your program should read lines from standard input. Each line contains two space-delimited lists. The lists are separated with a pipe char (|). Both lists have the same length, in range [1, 10]. Each element in the lists is a number in range [0, 99].
Output:
Print the multiplied list.
Test Input:
9 0 6 | 15 14 9
Expected Output:
135 0 54
Try this:
input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join([str(n1*n2) for n1, n2 in zip(list1, list2)])
OR,
input_string = input().strip()
list1 = input_string.split("|")[0].split()
list2 = input_string.split("|")[1].split()
result = " ".join([str(int(n1)*int(n2)) for n1, n2 in zip(list1, list2)])
OR,
import operator
input_string = input().strip()
list1 = map(int, input_string.split("|")[0].split())
list2 = map(int, input_string.split("|")[1].split())
result = " ".join(map(str, map(operator.mul, list1, list2)))
OUTPUT of print(result):
135 0 54
Since you are asking for help and not just a solution, here are some useful functions that should give you some inspiration:)
input("give me some") #reads a string from stdin.
"abcabcbbbc".split("c") #splits the string on "c" and returns a list.
int("123") #converts the string to an int object.
#Input comma seperated values
a = input("Values of first list: ")
a = a.split(",")
b = input("Valies of second list: ")
b = b.split(",")
c = []
counter = 0
for each in a:
c.append(int(each) * int(b[counter]))
counter += 1
I have a problem with the task, I need to input numbers and print it like a histogram with symbol ($). One unit is one ($) symbol.
For example:
input
1 5 3 2
print
$
$$$$$
$$$
$$
The code at the moment:
number = int(input())
while (number > 0):
print('$' * number)
number = 0
This works only with one number.
What need to do to code work properly?
You can do that like the follwoing,
>>> x = input("Enter the numbers: ") # use `raw_input` if `python2`
Enter the numbers: 1 2 3 4 5
>>> x
'1 2 3 4 5'
>>> y = [int(z) for z in x.split()]
>>> y
[1, 2, 3, 4, 5]
>>> for i in y:
... print('$' * i)
...
$
$$
$$$
$$$$
$$$$$
>>>
You're close and your thinking is right.
When you input() a string a numbers separated by a space, you need to convert each number into an integer, because by default all arguments are string for input.
You can use the map function to convert each input to integer.
inp = map(int, input().split())
Here input().split() converts 1 5 3 2 to ['1', '5', '3', '2']
Then applying map(int, [1, 5, 3, 2]) is equivalent to doing int(1), int(5) to each element.
Syntax of map: map(function, Iterable) function is int() in out case.
Then as you have the integers, all you need to do is take each value and print the number of '$'
for val in inp:
print('$'*val)
Here's the complete code:
inp = map(int, input().split())
for val in inp:
print('$'*val)
$
$$$$$
$$$
$$
You could try this
#get numbers as string
numbers = input('Enter numbers separated by <space> :')
# split numbers (create list)
nums = numbers.split(' ')
#loop each number
for num in nums:
print_num = ''
#create what to print
for i in range(int(num)):
print_num = print_num + '$'
#print
print(print_num)
numbers = raw_input("input :")
for number in [li for li in numbers.split(" ") if li.isdigit()]:
print('$' * int(number))