Test if set is a subset, considering the number (multiplicity) of each element in the set

前端 未结 5 1918
谎友^
谎友^ 2020-12-19 14:32

I know I can test if set1 is a subset of set2 with:

{\'a\',\'b\',\'c\'} <= {\'a\',\'b\',\'c\',\'d\',\'e\'} # True

But the following is a

5条回答
  •  情深已故
    2020-12-19 14:54

    Combining previous answers gives a solution which is as clean and fast as possible:

    def issubset(X, Y):
        return all(v <= Y[k] for k, v in X.items())
    
    • No instances created instead of 3 in @A.Rodas version (both arguments must already be of type Counter, since this is the Pythonic way to handle multisets).
    • Early return (short-circuit) as soon as predicate is falsified.

提交回复
热议问题