How does python max(list) function work? - python

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)

Related

Errors trying to append specific number of floats from user input

x={}
continueQ=input("would you like to continue?"))
if (continueQ=="yes"):
#if there is less than 4
if x<4:
variable=float(input("Input a float to append to the array:")
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
There are a few errors in this code, could someone help me how to create an if statement to check if there are minimum than 4 values inside an array .
Also how to append to an array from an input.
Create a list with x = [], Use len(x) to get the length of list, use while loop with condition if x<4
x=[]
continueQ=input("would you like to continue?")
if (continueQ=="yes"):
#if there is less than 4
while len(x)<4:
variable=float(input("Input a float to append to the array:"))
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
The first thing you'll want to do is change that x={} to an x=[]. What you've done is create a dictionary rather than an array, and consequently will run into an assortment of issues as you're dealing with the wrong data structure.
Once you've done that, we can move on to how to check if there are less than 4 values inside an array. In Python, arrays carry a length attribute, which can be accessed by writing len(arrayName), or in your case, len(x). For example, if your array x contained the following values: [1,2,3], then len(x) would return 3, seems simple enough.
Now to check that the length is less than 4, you need to replace your if x<4: with if len(x)<4:.
You already have the correct code to append to your array, it likely wasn't working before because you created a dictionary instead of an array.
There are several errors in your code. Here's a working version:
x = []
continueQ = input('Would you like to continue?')
if continueQ.lower() == 'yes':
while len(x) < 4:
variable=float(input('Input a float to append to the array:'))
x.append(variable)
print(x)
print("Goodbye!")
Explanation
[] represents an empty list, while {} is use for an empty set.
Make sure your bracketing is consistent; all open brackets must be closed.
Use len(x) to find the number of entries in a list x.
Use a while loop to repeat logic until a criterion is satisfied.

Taking input using for loop in python

a,b = int(i) for i in input().split()
Can someone explain why the above code doesn't work?
I understand I can use this to make a list like:
a = [int(i) for i in input().split()]
But why doesn't it work for 2 values? If a runtime exception rises(passing more than 2 values), termination is totally legit. But the shows invalid syntax.
I just checked. These are called Generator Functions. And the code can be modified as:
a,b = (int(x) for x in input().split())
Also, a,b = [int(x) for x in input().split()] also does the same job, but instead it return a list. The list is then iterated and is assigned to the variables at python's end. (Correct me if I am wrong)
Thanks to everyone who answered! :D

inputted list keeps being interpreted as string

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())

Create variables dynamically inside 'for' loop

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()]

Python truncating numbers in integer array

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.

Categories

Resources