-4

Having a problem recently when using the max() function in python. Here is my code:

x = ["AJK","exit","Down","World","HappyASD"]
max(x)

But instead of getting "HappyASD", I get "exit". Any help?

AlexKnight
  • 13
  • 1
  • 3

4 Answers4

4

If you are looking for the max by length, you need to send the key to the max function

x = ["AJK","exit","Down","World","HappyASD"]
max(x, key=len)

DEMO:

>>> x = ["AJK","exit","Down","World","HappyASD"]
>>> max(x, key=len)
'HappyASD'
>>> 

If the key is not specified, by default the max is determined by the coerced type.

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • I tried this and it works! Thanks, didn't realise you need to pass anything into the max() function (this is why I hate python). Going to mark this as correct. – AlexKnight Mar 10 '16 at 19:58
  • @AlexKnight: How do you expect Python to know that you want maximum by string length rather than its default ordering unless you tell it? – PM 2Ring Mar 10 '16 at 20:01
  • 2
    @AlexKnight i understand your frustration. Just give it some more time and you will start appreciate the flexibility and simplicity that Python provides.. It is the initial phases you might have a few hiccups with. But trust me, you will like it over time. – karthikr Mar 10 '16 at 20:02
  • 4
    "This is why I hate python", WUT??!? You should know the tools you want to use. You won't expect a car to tell you how to drive it right? – Mr. E Mar 10 '16 at 20:03
  • @karthikr I know, it's just I have been dabbling with C++, so naturally compare python. So that's why I get frustrated sometimes, but I would always recommend python for its simplicity. – AlexKnight Mar 10 '16 at 20:07
0

ord('e')=101 is higher than ord('H')=72

Matt Jordan
  • 2,133
  • 9
  • 10
0

can see no error in here... ord values of first letter in exit are the highest

Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
0

It is because the max() compares the ascii value of the character. I think. 'e' is 0x65, while, 'A' is 0x41, 'D' is 0x44 and so on.

you can refer to: http://www.tutorialspoint.com/python/string_max.htm

Qoros
  • 493
  • 7
  • 16