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?
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.
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.
The answer is: max() !
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.
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)
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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With