Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum of two tuples

Tags:

python

max

The Python documentation states that, when called with more than one argument, max() returns the largest of the arguments.

>>> a = (1, 1, 1, 9)
>>> b = (4, 5, 6)
>>> max(a, b)
(4, 5, 6)

What defines how large a tuple, in this context, is? The tuple a has both a higher number of elements (four versus three) and its maximum value (9) is greater than the maximum number that can be found in b (6), so by any criteria I would have expected it to be the returned one. How are the tuples being compared by max()?

like image 989
plok Avatar asked Mar 05 '12 23:03

plok


2 Answers

Tuples like all other sequences are ordered lexicographically: the order of two tuples is decided by the first position where the tuples differ. Quoting from python reference:

Tuples and lists are compared lexicographically using comparison of corresponding elements.

Your two tuples differ on the first position and since 4 > 1, we have

>>> (4, 5, 6) > (1, 1, 1, 9)
True
like image 109
Adam Zalcman Avatar answered Sep 23 '22 06:09

Adam Zalcman


From left to right it compares each element of the tuples until it finds one larger than the other. This tuple is then returned. For example

>>> a = (2,0,0,0)
>>> b= (1,1,1,1)
>>> max(a,b)
(2, 0, 0, 0)

>>> b = (2,1,1,1)
>>> max(a,b)
(2, 1, 1, 1)

After an element is found in one tuple that is larger than the respective element in the other the remaining values have no effect on which tuple is returned.

like image 21
MDT Avatar answered Sep 24 '22 06:09

MDT