Reputation: 57
Tuple1 = (1,2,2)
TupleList = [(1,2,3), (1,2,3,2)]
I want to search in TupleList for any tuple being a superset of Tuple1. The result should be in this case:
(1,2,3,2)
But if I use the .issuperset() function, it will not take into account the repetition of the 2 inside Tuple1.
How to solve this problem?
Upvotes: 0
Views: 157
Reputation: 17166
from collections import Counter
def contains(container, contained):
" True if all values in dictionary container >= values in contained"
return all(container[x] >= contained[x] for x in contained)
def sublist(lst1, lst2):
" Detects if all elements in lst1 are in lst2 with at least as many count "
return contains(Counter(lst1), Counter(lst2), )
Tuple1 = (1,2,2)
TupleList = [(1,2,3), (1,2,3,2)]
# List of tuples from TupleList that contains Tuple1
result = [x for x in TupleList if sublist(x, Tuple1)]
print(result)
>>>[(1, 2, 3, 2)]
Upvotes: 2
Reputation: 3534
If you need to consider element frequency this is probably a good use of the collections.Counter
utility.
from collections import Counter
tuple_1 = (1, 2, 2)
tuple_list = [(1, 2, 3), (3, 4, 1), (1, 2, 3, 2)]
def find_superset(source, targets):
source_counter = Counter(source)
for target in targets:
target_counter = Counter(target)
if is_superset(source_counter, target_counter):
return target
return None # no superset found
def is_superset(source_counter, target_counter):
for key in source_counter:
if not target_counter[key] >= source_counter[key]:
return False
return True
print(find_superset(tuple_1, tuple_list))
Output:
(1, 2, 3, 2)
Upvotes: 2