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())
Related
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)
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]
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).
I am teaching myself Python and am running into a strange problem. What I am trying to do is pass a list to a function, and have the function return a list where elements are the sum of the numbers around it, but what I thought would work produced some strange results, so I made a debug version of the code that still exhibts the behavior, which is as follows:
When I make an integer array, and pass it to an function which then uses a for loop print the individual values of the list, the numbers following the first one in each int are truncated.
For example, the following input and output:
Please enter a number: 101
Please enter a number: 202
Please enter a number: 303
Please enter a number: .
1
2
3
This happens no matter the input, if its 10, 101, or 13453 - the same behavior happens.
I know I am probably missing something simple, but for the sake of me, no amount of googling yields me a solution to this issue. Attached below is the code I am using to execute this. It is interesting to note: when printing the entire list outside of the for loop at any point, it returns the full and proper list (ie ['101', '202', '303'])
Thanks!
temp = list()
def sum(list):
print list
for i in range(1, len(list)+1):
print i
return temp
L = list()
while True:
input = raw_input("Please enter a number: ");
if input.strip() == ".":
break
L.append(input);
print L
L2 = sum(L)
print L2
The loop
for i in range(1, len(my_list)+1):
print i
iterates over the numbers from 1 to len(my_list), not over the items of the list. To do the latter, use
for x in my_list:
print x
(I've renamed list to my_list to save you another headache.)
You are printing the counter, not the list item. This is what you want:
for i in list:
print i
list is itself iterable and you don't need a counter to loop it.