Python: Find Tuples With Greatest Total Distinct Values
I have a list of tuples of integers. I would like to return a new list containing some (or all) of these tuples such that total number of integers is largest and no single integer
Solution 1:
I don't know if this is the most elegant solution, but it's the only one I have right now:
import itertools
#a = [(1,2), (2,3,4), (1,2,3,4), (3,4,5,6), (4,5), (8,9)]#a = [(1,), (2,), (3,), (4,), (5,), (5,6), (6,7), (8,), (9, 10)]
a = [(0, 1, 2), (0,1), (1,2), (3,4), (4,5)]
deffind_largest_group(x):
max_ = 0
max_len = max(map(max, x)) - min(map(min, x)) + 1for i inrange(1, len(x)+1):
b = itertools.combinations(x, i)
for tups in b:
m = len(set.union(*map(set, tups)))
if m==len(tuple(itertools.chain.from_iterable(tups))):
if m==max_len:
max_tups = tups
breakelse:
if m > max_:
max_ = m
max_tups = tups
return max_tups
output:
In [68]: find_largest_group(a)
Out[68]: ((0, 1, 2), (3, 4))
Solution 2:
He said that if they don't have repeating items, so the set won't give us the right result as if there is a tuple that has 10 elements but two are repeating (with a set it will have 9 elements) it should not be included. Following this logic, the best solution is to filter those tuples right away.
my_tuples = [(1,2), (2,3,4), (1,2,3,4), (3,4,5,6,1,2,7,5,6), (4,5), (8,9)]
print(max([i for i in my_tuples iflen(i)==len(set(i))], key=lambda x: len(x)))
Post a Comment for "Python: Find Tuples With Greatest Total Distinct Values"