简体   繁体   中英

Why does max() produce wrong output in python?

numbers=input("Enter numbers separated by space")
x=numbers.split()
mx=max(x)
print(mx)

Input is 4 5 29 54 4 0 -214 542 -64 1 -3 5 6 -6.

The output should be 542 but I'm getting the output as 6!

Convert them into integers and then apply function.

numbers=input("Enter numbers separated by space")
x=[int(i) for i in numbers.split()]
mx=max(x)
print(mx)

Output:

542

input is in string. You need to convert it to ints.

numbers=input("Enter numbers separated by space")
x=map(int, numbers.split())
mx=max(x)
print(mx)

#542

Others have explained whats going on but since Python has a repl, I'll use that to show you what python believes is happening.

>>> nums = input('insert space separated numbers ')
insert space separated numbers 1 2 3 4 5
>>> nums
'1 2 3 4 5'
>>> type(nums)
<class 'str'>
>>> nums.split(' ')
['1', '2', '3', '4', '5']
>>> type(nums.split(' '))
<class 'list'>

It all makes sense up to here. We read a string from user and when we split it, we get a list.

>>> type(nums.split(' ')[0])
<class 'str'>

This should still make sense but is what needs explaining. We split a string into a list of characters. In order to interpret that as an integer we need to call the int method on it.

>>> [int(x) for x in nums.split(' ')]
[1, 2, 3, 4, 5]

Putting it all together

>>> max([int(x) for x in nums.split(' ')])
5

To help explain more about above,

>>> '1' == 1
False
>>> '1' < 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  TypeError: '<' not supported between instances of 'str' and 'int'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM