Find common union groups among tuples in a set

93 Views Asked by At

I need help to write a function that:

  • takes as input set of tuples
  • returns the number of tuples that has unique numbers

Example 1:

# input:
{(0, 1), (3, 4), (0, 0), (1, 1), (3, 3), (2, 2), (1, 0)}

# expected output: 3

The expected output is 3, because:

  • (3,4) and (3,3) contain common numbers, so this counts as 1
  • (0, 1), (0, 0), (1, 1), and (1, 0) all count as 1
  • (2, 2) counts as 1

So, 1+1+1 = 3


Example 2:

# input:
{(0, 1), (2, 1), (0, 0), (1, 1), (0, 3), (2, 0), (0, 2), (1, 0), (1, 3)}

# expected output: 1

The expected output is 1, because all tuples are related to other tuples by containing numbers in common.

2

There are 2 best solutions below

2
Junior2345 On

this code works for me but check it maby there edge cases how this solution?

def count_groups(marked):
    temp = set(marked)
    save = set()
    for pair in temp:
        if pair[1] in save or pair[0] in save:
            marked.remove(pair)
        else:
            save.add(pair[1])
            save.add(pair[0])
    return len(marked)

image

0
Rodrigo Rodrigues On

This may not be the most efficient algorithm for it, but it is simple and looks nice.

from functools import reduce

def unisets(iterables):
  def merge(fsets, fs):
    if not fs: return fsets
    unis = set(filter(fs.intersection, fsets))
    return {reduce(type(fs).union, unis, fs), *fsets-unis}
  return reduce(merge, map(frozenset, iterables), set())

us = unisets({(0,1), (3,4), (0,0), (1,1), (3,3), (2,2), (1,0)})
print(us)       # {frozenset({3, 4}), frozenset({0, 1}), frozenset({2})}
print(len(us))  # 3

Features:

  • Input can be any kind of iterable, whose elements are iterables (any length, mixed types...)
  • Output is always a well-behaved set of frozensets.