What does max do in the list of sets?

max takes an iterative parameter and will return the maximum value for iterable. For integers, this is an obvious behavior, as it can simply determine which number is the largest. For characters, lexicographical ordering is used instead:

 >>> 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 ordered ordering works, although I believe this is just 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 this is not what creates 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 does Python determine the max value in this case?

+5
source share
1 answer

< is the correct subset operator in python. This is not a length comparison.

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

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

+6
source

Source: https://habr.com/ru/post/1237567/


All Articles