xue
xue

Reputation: 11

How to define the “largest” set in python?

Consider following code:

b = set([111,222,333,444])
a = set([10,20,30])
print max(a,b,key=len) # set([444, 333, 222, 111])
print max(a,b) # set([10, 20, 30])

I am curious, if there is no ‘key’ parameter, the max() function will return a confusing result, it is not the one contains more items, neither the one whose first item is bigger (10<111), neither the first argument (if it doesn’t know how to compare the input arguments, maybe it will return the first argument which is b?)

By the explanation of max() function, it should return “the largest argument” if the input is two or more argument. So how to define the ‘largest’ among several sets?

Upvotes: 0

Views: 170

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1123440

Sets override <, <=, > and >= to make subset and superset comparisons and should not be seen as orderable.

Because of this, there is no 'max' or 'min' set.

From the set type documentation:

issubset(other)
set <= other

Test whether every element in the set is in other.

set < other

Test whether the set is a proper subset of other, that is, set <= other and set != other.

issuperset(other)
set >= other

Test whether every element in other is in the set.

set > other

Test whether the set is a proper superset of other, that is, set >= other and set != other.

and further down

A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal).

and finally

Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets.

max() and min() use the same definitions of ordering to determine the largest or smallest item from a series of inputs, and because sets define ordering in terms of subset relationships, the output of max() and min() is undefined too.

Upvotes: 5

Related Questions