SuperBiasedMan
SuperBiasedMan

Reputation: 9969

What does max do on a list of sets?

max takes an iterable parameter and will return the maximum value for the iterable. For integers this is obvious behaviour as it can just determine which number is largest. For characters it instead uses Lexicographic ordering:

>>> max("hello world!")
'w'
>>> 'w' > 'r'
True
>>> max("Hello World!")
'r'
>>> 'W' > 'r'
False

However, what does Python do with a list of sets? It's unclear how set's ordering works, though I believe it's just to do with length:

>>> set([1]) < set([5])
False
>>> set([1]) > set([5])
False
>>> set([1]) < set([1, 2])
True
>>> set(range(5)) < set(range(7)) < set(range(1000))
True

But that's not what produces the max value:

>>> max([set([1]), set([5]), set([2, 4, 7]), set([100000])])
set([1])
>>> max([set([]), set([11]), set([5]), set([2, 4, 7]), set([100000])])
set([11])
>>> max([set(range(45)), set(range(12)), set(range(100, 1260, 40))])
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44])

How is Python determining the max value in this case?

Upvotes: 5

Views: 562

Answers (1)

Evan
Evan

Reputation: 756

< is the proper subset operator in python. It is not comparing length.

https://docs.python.org/2/library/stdtypes.html#set.issubset

set([]) < set([11]) is True because the first is a proper subset of the second, but set([11]) is not a proper subset of any of the later sets. The natural implementation of max uses <, so it's not too surprising for it to return set([11]) here.

Upvotes: 6

Related Questions