5

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?

1
  • 1
    It's doing exactly what it should be doing, '9' > '10' but 10 > 9. You need to cast the values of the list to integers before comparing them Commented Aug 3, 2018 at 2:14

3 Answers 3

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

can you explain what map is doing please?
2

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.