Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list is a subset of another list

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]

like image 582
dimka Avatar asked Dec 01 '22 02:12

dimka


2 Answers

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
like image 57
Santa Avatar answered Dec 03 '22 14:12

Santa


Just in order to offer an alternative, perhaps using tuple and set is more efficient:

>>> set(map(tuple,listB)) <= set(map(tuple,listA))
True
like image 42
fransua Avatar answered Dec 03 '22 15:12

fransua