2

hello I am kind of confused about the max() function, I have the following code:

a = '9:30'
b = '10:44'
c = '8:22'
x = max(a, b, c)
print (x)

so my question is: why does this return 9:30? and if I were to delete the a from inside max it would return 8:22

YoungDanEn
  • 27
  • 1
  • 8

7 Answers7

5

String a compares as the biggest because it starts with 9 and the other strings start with 1 and 8. Python therefore returns '9:30' as the maximum value out of those three strings.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
2

As you are doing string comparison the int or ASCII value of '9' is greater than '8' and '1'. You can see the int value of individual char using ord built-in function.

>>> ord('9')
57
>>> ord('1')
49
>>> ord('8')
56

And as Python does comparison in lexicographical manner(from left to right each char). It finds value of '9' greater. And if you delete '9' if finds '8''s value greater than '1'.

One way to achieve could be :-

a = '9:30'
b = '10:44'
c = '8:22'
d = '10:55'

print max([a, b, c, d], key=lambda x: map(int, x.split(':')))
Community
  • 1
  • 1
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43
1

Its because of that max function will find the max value lexicographicaly , you can use a proper key for max function to convert the hour and min to int.

>>> l=[a,b,c]
>>> max(l,key=lambda d :map(int, d.split(":")))
'10:44'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

Since it's arguments are strings, it is returning the string that is latest in alphabetic order.

Craig Burgler
  • 1,749
  • 10
  • 19
0

it is comparing strings, and, as such, it starts by comparing the first character, and then, if that character is the same, moves on to the next and then the next etc etc.

So '9:30' is returned because 9 > 8 > 1. If you want "10:44" to return, then you should use the datetime module, unless you want to write custom code for that

edit: and sniped by people who type faster!

Matthew
  • 672
  • 4
  • 11
0

You are comparing strings, not numbers or times. As such, it compares the strings by their first character (and if those are equal, by the second, and so on), and the first character of "9:30" is the highest.

If you want to compare the times, you can split the string at the :symbol, map the parts to integers and compare those, using an according key function.

x = max([a, b, c], key=lambda s: map(int, s.split(":")))
tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

Here's another way to do it so you can just use the regular max function. First, pad the strings so that "9" becomes "09" and "10" stays "10". You can use str.zfill for this:

a = '9:30'
b = '10:44'
c = '8:22'
a, b, c = map(lambda s: s.zfill(5), (a, b, c))

Now, they will be what you want lexicographically!

print(max([a, b, c]))
10:44

You only have to pad them once, but you will be stuck with:

print(min([a, b, c]))
08:22