What's wrong with this program in Python?
I need to take an integer input(N) - accordingly, I need to create an array of (N)integers, taking integers also as input. Finally, I need to print the sum of all the integers in the array.
The input is in this format:
5
4 6 8 18 96
This is the code I wrote :
N = int(input().split())
i=0
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = int(input().split())
V.append(x)
i+=1
s+=x
print (s)
Its showing the following error.
Traceback (most recent call last):
File "main.py", line 1, in <module>
N = int(input().split())
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
split() returns a list which you are trying to convert to an integer.
You probably wanted to convert everything in the list to an integer:
N = [int(i) for i in input().split()]
You can also use map:
N = list(map(int, input().split()))
You could use sys module to take the input when calling the program and a lambda function to convert the string items in list to integers. You could also make use of the built-in sum function. Something like that:
#!/usr/bin/env python
import sys
s = sum(i for i in map(lambda x: int(x), sys.argv[1].split(',')))
print s
Example:
python test.py 1,2,3,4
The output should be 10.
Modifying your code:
Now, if you want to modify your code to do what it intends to do, you could modify your code like that:
#!/usr/bin/env python
N = input()
s = 0
V=[]
if N<=100 :
for i in range (0,N):
x = input()
V.append(x)
s+=x
print (s)
Note 1: In python when you use range you don't have to manually increase the counter in the loop, it happens by default.
Note 2: the 'input()' function will maintain the type of the variable you will enter, so if you enter an integer you don't have to convert it to integer. (Have in mind that input() is not recommended to use as it can be dangerous in more complicated projects).
Note 3: You don't need to use '.split()' for your input.
You code fails because str.split() returns a list.
From the Python documentation
Return a list of the words in the string, using sep as the delimiter
string
If your input is a series of numbers as strings:
1 2 3 4
You'll want to iterate over the list returned by input.split() to do something with each integer.
in = input()
for num in in.split():
x.append(int(num))
The result of this will be:
x = [1,2,3,4]
Related
I'm new to python and I'm trying to scan multiple numbers separated by spaces (let's assume '1 2 3' as an example) in a single line and add it to a list of int. I did it by using:
#gets the string
string = input('Input numbers: ')
#converts the string into an array of int, excluding the whitespaces
array = [int(s) for s in string.split()]
Apparently it works, since when I type in '1 2 3' and do a print(array) the output is:
[1, 2, 3]
But I want to print it in a single line without the brackets, and with a space in between the numbers, like this:
1 2 3
I've tried doing:
for i in array:
print(array[i], end=" ")
But I get an error:
2 3 Traceback (most recent call last):
print(array[i], end=" ")
IndexError: list index out of range
How can I print the list of ints (assuming my first two lines of code are right) in a single line, and without the brackets and commas?
Yes that is possible in Python 3, just use * before the variable like:
print(*list)
This will print the list separated by spaces.
(where * is the unpacking operator that turns a list into positional arguments, print(*[1,2,3]) is the same as print(1,2,3), see also What does the star operator mean, in a function call?)
You want to say
for i in array:
print(i, end=" ")
The syntax i in array iterates over each member of the list. So, array[i] was trying to access array[1], array[2], and array[3], but the last of these is out of bounds (array has indices 0, 1, and 2).
You can get the same effect with print(" ".join(map(str,array))).
Try using join on a str conversion of your ints:
print(' '.join(str(x) for x in array))
For python 3.7
these will both work in Python 2.7 and Python 3.x:
>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3
btw, array is a reserved word in Python.
You have multiple options, each with different general use cases.
The first would be to use a for loop, as you described, but in the following way.
for value in array:
print(value, end=' ')
You could also use str.join for a simple, readable one-liner using comprehension. This method would be good for storing this value to a variable.
print(' '.join(str(value) for value in array))
My favorite method, however, would be to pass array as *args, with a sep of ' '. Note, however, that this method will only produce a printed output, not a value that may be stored to a variable.
print(*array, sep=' ')
If you write
a = [1, 2, 3, 4, 5]
print(*a, sep = ',')
You get this output: 1,2,3,4,5
# Print In One Line Python
print('Enter Value')
n = int(input())
print(*range(1, n+1), sep="")
lstofGroups=[1,2,3,4,5,6,7,8,9,10]
print(*lstofGroups, sep = ',')
don't forget to put * before the List
For python 2.7 another trick is:
arr = [1,2,3]
for num in arr:
print num,
# will print 1 2 3
you can use more elements "end" in print:
for iValue in arr:
print(iValue, end = ", ");
Maybe this code will help you.
>>> def sort(lists):
... lists.sort()
... return lists
...
>>> datalist = [6,3,4,1,3,2,9]
>>> print(*sort(datalist), end=" ")
1 2 3 3 4 6 9
you can use an empty list variable to collect the user input, with method append().
and if you want to print list in one line you can use print(*list)
I have the following code that doesn't work the way it should.
n = int(input())
arr = map(int, input().split())
num=max(arr)
x=list(set(arr))
print (x)
This returns and empty list "[]".
However, if I remove the num=max[arr] line from the code, it works as expected.
n = int(input())
arr = map(int, input().split())
x=list(set(arr))
print (x)
And the output is a list of all elements without duplicates.
I wanted to use the max() value somewhere else in the program, but it seems to break the list formation. Why does this happen? Is there a basic property of the max function that I'm missing?
Edit: Why are people downvoting this without any answers? I'm fairly new to python and any help would be appreciated. If I made a silly mistake please point that out.
n = int(input()) # unused - why put it in your example?
arr = map(int, input().split()) # returns an iterator
num=max(arr) # consumes the iterator
x=list(set(arr)) # nothing in the iterator anymore
print (x) # prints nothing
Fix:
n = int(input()) # unused - why put it in your example?
arr = set(map(int, input().split())) # returns an set named arr
num=max(arr) # get num as max from set
print (arr) # prints the set named arr
In python 2 map behaved differently - for 3 its an iterator. Once consumed, iterators are "empty". You can see for yourself if you print(type(arr)) for the result of your map operation.
Read: map()
I'm not sure why you need to use map in this case. Another thing is that you will throw errors on your input if the user does not provide a single int since you are trying to convert it. You can take your input, like a string of '1 4 6 23 5', convert it to a list of ints, and then find the max.
n = '1 4 6 23 5'
arr = [int(x) for x in n.split()]
max(arr)
So I made this little code at school, and i know that input() can understand lists as is. I tried it again at home but it doesnt work. My school computer has python 2. something while my laptop has 3.4.
The code looks like this
a = input()
list = []
count = 0
for y in range(1, len(a)):
min = a[count]
for x in range(count +1, len(a)):
if min > a[x]:
min = a[x]
print(min)
a[count] = min #str object does not support item assignment
count=count+1
print (a)
I want to input a list such as [1,2,3,4,5] but what happens is, it reads the whole thing as a string, along with the commas, when i want to see it as a list of integers.
Python 3's input returns a string (same as Python 2's raw_input), whilst Python 2's input evaluates the text. To get similar behaviour, if you've got a valid Python list that can be evaluated, then you can use ast.literal_eval, eg:
import ast
a = ast.literal_eval(input())
# do other stuff with `a` here...
So you'd enter something like [1, 2, 3, 4, 5] as your input, and you'll end up with a being a Python list.
I assume your input would be something like: "1 2 3 4 5" -- judging by the code which comes later. This oufcourse is a string. If you want to work with the numbrs in the string as integers you need to:
a = input()
a = map(int, a.split())
I'm new to python and trying to take some coding challenges to improve my skills. I've to take input in following ways:
2
3 1
4 3
First, I get number of test cases.(2 here) Then based on that, I've to get given number of test cases that are each 2 integers. 1st is the range and second is the number to be searched in the range.
What's the correct, pythonic way of getting the input. I was thinking like this but it's obviously incorrect
num_testcases = int(raw_input())
for i in num_testcases:
range_limit = int(raw_input())
num_to_find = int(raw_input())
raw_input() is going to be read one line at a time from STDIN, so inside the loop you need to use str.split() to get the value of range_limit and num_to_find. Secondly you cannot iterate over an integer(num_testcases), so you need to use xrange()(Python 2) or range()(Python 3) there:
num_testcases = int(raw_input())
for i in xrange(num_testcases): #considering we are using Python 2
range_limit, num_to_find = map(int, raw_input().split())
#do something with the first input here
Demo:
>>> line = '3 1'
>>> line.split()
['3', '1']
>>> map(int, line.split())
[3, 1]
Note that in Python 3 you'll have to use input() instead of raw_input() and range() instead of xrange(). range() will work in both Python 2 and 3, but it returns a list in Python 2, so it is recommended to use xrange().
Use for i in range(num_testcases): instead of for i in num_testcases. Have a look at range (or xrange in Python 2). range(a) produces an iterable from 0 to a - 1, so your code gets called the desired number of times.
Also, input and raw_input take input on encountering a newline, meaning that in range_limit = int(raw_input()), raw_input returns "3 1", which you can't just convert to int. Instead, you want to split the string using string.split and then convert the individual items:
num_testcases = int(raw_input())
for i in range(num_testcases):
range_limit, num_to_find = [int(x) for x in raw_input().split()]
I want to know how can I add these numbers in Python by using a loop? Thanks
num=input("Enter your number: ")
ansAdd= int(str(num)[7])+int(str(num)[5])+int(str(num)[3])+int(str(num)[1])
print....
you want to do it using a loop, here you go:
ansAdd = 0
for x in [7,5,3,1]:
ansAdd += int(str(num)[x])
However, using list comprehension is more pythonic
>>> s = '01234567'
>>> sum(map(int, s[1::2]))
16
Here is how it works:
s[1::2] takes a slice of the string starting at index 1 to the end of the string stepping by 2. For more information on slices see the Strings section of the Python Tutorial.
map takes a function and an iterable (strings are iterable) and applies the function to each item, returning a list of the results. Here we use map to convert each string-digit to an int.
sum takes an iterable and sums it.
If you want to do this without the sum and map builtins, without slices, and with an explicit for-loop:
>>> s = '01234567'
>>> total = 0
>>> for i in range(1, len(s), 2):
... total += int(s[i])
...
>>> total
16
>>> num=input()
12345678
>>> sum(map(int,num[:8][1::2]))
20
here num[:8][1::2] returns only the numbers required for sum(), num[:8] makes sure only the elemnets up to index 7 are used in calculation and [1::2] returns 1,3,5,7
>>> num[:8][1::2]
>>> '2468'
It seems you want to sum odd-numbered digits from user input. To do it with a loop:
num_str = raw_input("Enter your number: ")
ansAdd = 0
for digit in num_str[1::2]:
ansAdd += int(digit)
(The syntax [1::2] is python's string slicing -- three numbers separated by : that indicates start index, stop index and step. An omitted value tells python to grab as much as it can.)
There's a better way to do this without using a traditional loop:
num_str = raw_input("Enter your number: ")
ansAdd = sum(int(digit) for digit in num_str[1::2])
In python 2, input executes the entered text as python code and returns the result, which is why you had to turn the integer back into a string using str.
It is considered a security risk to use input in python 2, since the user of your script can enter any valid python code, and it will be executed, no questions asked. In python 3 raw_input has been renamed to input, and the old input was removed (use eval(input()) instead).