L=input().split(' ')
for i in L:
c=float(i)
print(int(c), sep=",")
A sequence of numbers separated by space is to be accepted from user, the numbers are converted to the greatest integer less than or equal to the number and then printed.
I wanted to print the output on same line, but my code doesn't work
Thanks in advance....
You are looping through the list, change to float and put it into variable c. That loop is essentially meaningless. After that loop c contains the last value in the iteration. Just print the result at once:
L=input().split(' ')
all_ints = map(int, L)
print(*all_ints, sep=',')
Or using str.join:
print(','.join(map(str, all_ints)))
Or using a loop:
for i in all_ints:
print(i, end=',')
To get them all as floats you can use map as well:
all_floats = list(map(float, L))
I think this should work for you:
L = input().split(' ')
for i in L:
c = float(i)
print(int(c), end=" ")
Related
I was attempting to do one kata problem in Python, where I have two lists of input, let's say weight and value, which was getting input in the order (value1, weight1, value2, weight2,....)
If it were C++, I could just take one element at a time with cin to my arrays. But with Python I don't know how to take this input.
If the input is like
60 10 100 20 120 30 (in a single line)
I want my two lists val and w have values
val=[60,100,120]
w=[10,20,30]
How to take this kind of inputs in Python? Is it possible to read only one input at a time, like cin does in C++?
You can read space-separated input to a list using splitand then use slicing to get the odd/even indexed elements:
val = input().split()
val = [int(i) for i in val] #to integer
w = val[1::2] # get only odd indices
val = val[0::2] # get only even indices
print(val) # [60,100,120]
print(w) # [10,20,30]
You can then use regular indexing to get individual elements in the lists.
This should do it.
values = input("Enter values: ").split(" ")
if(len(values) % 2 != 0):
print("Error, uneven number of values and weights")
else:
val = []
w = []
for i in range(0, len(values) - 1, 2):
val.append(values[i])
w.append(values[i+1])
print("val: ", val)
print("w: ", w)
No you cannot as far as I know. input() is a function that reads one line at a time as an entire string.
A popular way to make a list out of an entire line of space separated integers is using the in-built map() function and split() method of a string object:
numbers = map(int, input.split())
numbers will now contain the list of numbers on that line.
Firstly, input() reads the entire line as a string including spaces.
split() function splits the input at space, you can also pass in a string argument to make it split anywhere you want, i.e a custom delimiter like , and creates a list of strings of those numbers
map() calls int() on each of the numbers in that list.
In C++, just like you need to know the size of input in advance, you can run a for loop on the list to now split values and weights into two lists.
val, w = [], []
for i in range(len(numbers)):
if i % 2 == 0: val.append(numbers[i])
else: w.append(numbers[i])
For better performance(relevant for large input size), you can even skip the map() step, and do something like this:
numbers = input().split()
val, w = [], []
for i in range(len(numbers)):
if i % 2 == 0: val.append(int(numbers[i]))
else: w.append(int(numbers[i]))
Here's a simple solution:
a = "60 10 100 20 120 30"
split_a = a.split(" ")
val = [e for (i, e) in enumerate(split_a) if i % 2 == 0]
w = [e for (i, e) in enumerate(split_a) if i % 2 == 1]
# or shorter with slicing (start:stop:step)
val = [e for e in split_a[0::2]]
w = [e for e in split_a[1::2]]
I am not sure what cin does but I assume the input you have is a string. One way you could do is to split it into a list of ints. And then create your val and w lists and append your values into the lists. (The first, third, fifth, etc would be your val list)
my_input_list = my_input.split(' ')
Read more here.
Usually, we input() a list in Python 3.X like this:
x = list(map(int, input()))
print (x)
But here let's say we give an input of 1234 then it prints:`
[1, 2, 3, 4]
Is there a way that I can print it like:
[12, 34]
Thanks in Advance!
Let's say you want the numbers to be entered separated by spaces. First get the entire line as input:
line = input()
Now parse the input. In this case, split on spaces:
words = line.split(' ')
Finally, convert each "word" to an int:
numbers = [int(i) for i in words]
Of course you can use map() instead of a list comprehension.
Note that this requires input such as
12 34
You can do this all in one line, but it is better to use variables to store each intermediate step. When you get it wrong, you can debug much more easily this way.
In my opinion, I would not complicate things :
I would declare an empty list :
l = []
Then I would simply append the input :
for i in range(0, n):
print("l[", i, "] : ")
p = int(input())
l.append(p)
You can notice here the "n",it's the size for the list,in your case it would be:
for i in range(0, 1):
print("l[", i, "] : ")
p = int(input())
l.append(p)
We always start from 0,so range(0,1) would count 0, then 1 and so on with other cases.
Hope this would help.
I just started learning Python and want to create a simple script that will read integer numbers from user input and print their sum.
The code that I wrote is
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += inflow[i]
print(result)
It gives me an error
IndexError: list index out of range
pointing to result += inflow[i] line. Can't see what am I doing wrong?
BTW, is there more elegant way to split input flow to the list of integers?
You can also avoid the loop altogether:
inflow = '1 2 34 5'
Then
sum(map(int, inflow.split()))
will give the expected value
42
EDIT:
As you initialize your result with 1 and not 0, you can then also simply do:
sum(map(int, input.split()), 1)
My answer assumes that the input is always valid. If you want to catch invalid inputs, check Anton vBR's answer.
Considering: I just started learning Python
I'd suggest something like this, which handle input errors:
inflow = raw_input("Type numbers (e.g. '1 3 5') ") #in py3 input()
#inflow = '1 2 34 5'
try:
nums = map(int, inflow.split())
result = sum(nums)
print(result)
except ValueError:
print("Not a valid input")
for i in list gives the values of the list, not the index.
inflow = list(map(int, input().split(" ")))
result = 1
for i in inflow:
result += i
print(result)
If you wanted the index and not the value:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And finally, if you wanted both:
for index, value in enumerate(inflow):
script that will read integer numbers from user input and print their
sum.
try this :
inflow = list(map(int, input().split(" ")))
result = 0
for i in inflow:
result += i
print(result)
If you were going to index the list object you would do:
for i in range(len(inflow)):
result += inflow[i]
However, you are already mapping int and turning the map object into a list so thus you can just iterate over it and add up its elements:
for i in inflow:
result += i
As to your second question, since you arent doing any type testing upon cast (i.e. what happens if a user supplies 3.14159; in that case int() on a str that represents a float throws a ValueError), you can wrap it all up like so:
inflow = [int(x) for x in input().split(' ')] # input() returns `str` so just cast `int`
result = 1
for i in inflow:
result += i
print(result)
To be safe and ensure inputs are valid, I'd add a function to test type casting before building the list with the aforementioned list comprehension:
def typ(x):
try:
int(x)
return True # cast worked
except ValueError:
return False # invalid cast
inflow = [x for x in input().split(' ') in typ(x)]
result = 1
for i in inflow:
result += i
print(result)
So if a user supplies '1 2 3 4.5 5 6.3 7', inflow = [1, 2, 3, 5, 7].
What your code is doing, in chronological order, is this:
Gather user input, split per space and convert to integer, and lastly store in inflow
Initialize result to 1
Iterate over every item in inflow and set item to i
Add the current item, i to result and continue
After loop is done, print the result total.
The broken logic would be at step 4.
To answer your question, the problem is that you're not gathering the index from the list as expected-- you're iterating over each value in the list opposed to the index, so it's really undefined behavior based on what the user inputs. Though of course, it isn't what you want.
What you'd want to do is:
inflow = list(map(int, input().split(" ")))
result = 1
for i in range(len(inflow)):
result += inflow[i]
print(result)
And on your last regard; there are two real ways to do it, one being the way you're doing right now using list, map and:
inflow = [int(v) for v in input().split()]
IMO the latter looks better. Also a suggestion; you could call stdlib function sum(<iterable>) over a list of integers or floats and it'll add each number and return the summation, which would appear more clean over a for loop.
Note: if you're splitting per whitespace you can just call the str.split() function without any parameters, as it'll split at every whitespace regardless.
>>> "hello world!".split()
['hello', 'world!']
Note: also if you want extra verification you could add a bit more logic to the list comprehension:
inflow = [int(v) for v in input().split() if v.isdigit()]
Which checks whether the user inputted valid data, and if not, skip past the data and check the following.
I have a code that print x number of numbers. Firstly, I asked for the serious length. Then print all the previous numbers (from 0 to x).
My question is that:
when printing these number, I want to separate between them using comma. I used print(a,end=',') but this print a comma at the end also. E.g. print like this 1,2,3,4,5, while the last comma should not be there.
I used if statement to overcome this issue but do not know if there is an easier way to do it.
n=int(input("enter the length "))
a=0
if n>0:
for x in range(n):
if x==n-1:
print(a,end='')
else:
print(a,end=',')
a=a+1
The most Pythonic way of doing this is to use list comprehension and join:
n = int(input("enter the length "))
if (n > 0):
print(','.join([str(x) for x in range(n)]))
Output:
0,1,2
Explanation:
','.join(...) joins whatever iterable is passed in using the string (in this case ','). If you want to have spaces between your numbers, you can use ', '.join(...).
[str(x) for x in range(n)] is a list comprehension. Basically, for every x in range(n), str(x) is added to the list. This essentially translates to:
data = []
for (x in range(n))
data.append(x)
A Pythonic way to do this is to collect the values in a list and then print them all at once.
n=int(input("enter the length "))
a=0
to_print = [] # The values to print
if n>0:
for x in range(n):
to_print.append(a)
a=a+1
print(*to_print, sep=',', end='')
The last line prints the items of to_print (expanded with *) seperated by ',' and not ending with a newline.
In this specific case, the code can be shortened to:
print(*range(int(input('enter the length '))), sep=',', end='')
what i want to do is take a string and for each character make the ordinal value 1 more from the value it has.
myinput=input("Message : ")
mylist =list(myinput) #convert to list in order to take each character
for character in mylist:
mylist[character]+=ord(mylist[character])+1
print(character)
The problem is with the "ord(mylist[character])+1"
Thank you!
Probably you are looking for the next:
>>> m = raw_input('Message:')
Message:asdf
>>> ''.join(chr(ord(c) + 1) for c in m)
'bteg'
Notes:
use raw_input when you need to get string input from a user;
ord convert character to integer, chr - vise versa;
... for c in m syntax is a generator expression. It is also used for list comprehension.
Three problems here. First, you're mixing up list indices and list elements. Second, you didn't convert back to a character (I'm assuming you want characters, not numbers). Third, you're adding to the existing value.
One way:
for i range(len(mylist)):
mylist[i] = chr(ord(mylist[i])+1)
Another way:
for i, character in enumerate(mylist):
mylist[i] = chr(ord(character)+1)
Instead of
for character in mylist:
mylist[character]+=ord(mylist[character])+1
(where character is a list index and therefore invalid), you probably want:
mylist = [ord(character) + 1 for character in mylist]
Or a Counter.
You can do like this
def ordsum(astring, tablesize):
sum = 0
for num in range(len(astring)):
sum = sum + ord(astring[num])
return sum
myinput = input() # use raw_input() in Python 2
myinput = map(lambda ch: chr(ord(ch) + 1), myinput)
# or list comp.
myinput = [chr(ord(ch) + 1) for ch in myinput]
You can iterate directly over a string, you do not have to make it a list first. If your end goal is to have a new string, you can do this:
myinput=input("Message : ")
result = []
for character in myinput:
result.append( chr( ord( character ) + 1 )
mynewstring = ' '.join(result)