in Python, given two lists of pairs:
listA = [ [1,20], [3,19], [37,11], [21,17] ]
listB = [ [1,20], [21,17] ]
how do you efficiently write a python function which return True if listB is a subset of listA? oh and [1,20] pair is equivalent to [20,1]
Use frozenset
.
>>> listA = [ [1,20], [3,19], [37,11], [21,17] ]
>>> listB = [ [1,20], [21,17] ]
>>> setA = frozenset([frozenset(element) for element in listA])
>>> setB = frozenset([frozenset(element) for element in listB])
>>> setA
frozenset([frozenset([17, 21]), frozenset([1, 20]), frozenset([11, 37]), frozens
et([19, 3])])
>>> setB
frozenset([frozenset([17, 21]), frozenset([1, 20])])
>>> setB <= setA
True
Just in order to offer an alternative, perhaps using tuple and set is more efficient:
>>> set(map(tuple,listB)) <= set(map(tuple,listA))
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With