Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 Max Function

Here is my code

def max_array_diff(line):
    return max(line)

line = raw_input().split()
print max_array_diff(line)
print line

Here is the output I am getting

9
['1', '9', '2', '-7', '10', '4', '3']

I need my output to be 10. raw_input() is coming in as a string, I have converted it to a list and am trying to get the max value from it but it keeps returning 9 instead of 10. What am I doing wrong?

like image 593
Branden Avatar asked Aug 03 '18 02:08

Branden


People also ask

How does Max () work in Python?

The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.

How do you find the maximum between two numbers in Python?

max() function: The max() function in Python is used to return the maximum of all the elements passed as arguments. Arguments: The method can accept any number of values. Return Type: the method returns the largest value out of all values.

Which function returns the maximum of 2 numbers?

The answer is: max() !

Is there a max value in Python?

As we have discussed above, there is no limit or maximum value of an integer in Python 3, but there is a limit for integer in Python 2, after which the data type of the variable switches to a long data type. In Python 3, the sys. maxint does not exist as there is no limit or maximum value for an integer data type.


3 Answers

You should convert the input to integers after splitting them; otherwise you'd be doing string comparisons with max().

Change:

line = raw_input().split()

to:

line = map(int, raw_input().split())

Alternatively, you can specify int as the key function for max() so that comparisons would be made based on the integer values of the string inputs.

Change:

return max(line)

to:

return max(line, key=int)
like image 123
blhsing Avatar answered Oct 20 '22 12:10

blhsing


You need to do integer compare instead of string compare:

def max_array_diff(line):
    return max(line)

line = [int(x) for x in raw_input().split()]
print max_array_diff(line)
print line
like image 2
jh314 Avatar answered Oct 20 '22 12:10

jh314


Or another way is to do:

print(sorted(raw_input().split(),key=int))

To get the highest do:

print(sorted(raw_input().split(),key=int)[0])

To get Top 3:

print(sorted(raw_input().split(),key=int)[:3])
like image 1
U12-Forward Avatar answered Oct 20 '22 13:10

U12-Forward