Compare tuples of different lenght
Peter Otten
__peter__ at web.de
Sat Aug 20 07:56:18 EDT 2011
Jurgens de Bruin wrote:
> Hi,
>
> I have a list of tuples:
>
> [(2,),(12,13),(2,3,4),(8,),(5,6),(7,8,9),]
>
> I would like to compare all the tuples to each other and if one
> element if found two tuples the smallest tuples is removed from the
> list.
>
> example if tuple 1 and tuple 3 are compare it should find that a
> single element in each are the same and tuple 1 should be removed
> resulting in
>
> [(12,13),(2,3,4),(8,),(5,6),(7,8,9),]
>
> the same for tuple 4 and 6 resulting in
>
> [(12,13),(2,3,4),(5,6),(7,8,9),]
>
> is this possible as I am having no success.
>
> Thanks
from collections import Counter, defaultdict
from itertools import chain
def process_counter(sample):
c = Counter()
d = defaultdict(list)
for items in sample:
c.update(items)
d[len(items)].append(items)
result = []
for cluster in sorted(d.values(), key=len):
c.subtract(chain.from_iterable(cluster))
for items in cluster:
if not any(c[item] for item in items):
result.append(items)
result.sort(key=sample.index)
return result
if __name__ == "__main__":
for process in [process_counter]:
print process.__name__
sample = [(2,),(12,13),(2,3,4),(8,),(5,6),(7,8,9),]
wanted = [(12,13),(2,3,4),(5,6),(7,8,9),]
assert process(sample) == wanted
sample = [(5,6), (6,7,8)]
wanted = [(6,7,8)]
got = process(sample)
assert got == wanted
sample = wanted = [(5, 6), (6, 7)]
assert process(sample) == wanted
sample = [(1,), (1, 2), (2, 3, 4)]
wanted = [(2, 3, 4)]
assert process(sample) == wanted
More information about the Python-list
mailing list