user7123790
user7123790

Reputation:

Checking if a set of tuple contains items from another set

Let's say I have a set of tuples like this:

foo = {('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')}
var = {'A', 'C', 'B'}

I want to check if every item from var is in any place in the set of tuples and returning True if it is and False if it isn't. I tried with this but I don't have luck so far.

all((x for x in var) in (a,b) for (a,b) in foo)
Desired output : True
Actual output : False

However if:

var = {'A','C','D'} 

I want it to return False, the logic is checking if the strings 'know' eachother.

Alright, let's explain this, for my last var.

A is paired with C, C is paired D, however D is not paired with A.

For my first logic,

A is paired with B,B is paired with C,C is paired with B, C is paired with A, Everyone 'knows' each other.

.

Upvotes: 0

Views: 2067

Answers (3)

Alex Hall
Alex Hall

Reputation: 36013

Generate all the pairs you expect to be present and see if they're there with a subset check:

from itertools import combinations

def _norm(it):
    return {tuple(sorted(t)) for t in it}

def set_contains(foo, var):
    return _norm(combinations(var, 2)) <= _norm(foo)

print(set_contains({('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')},
                   {'A', 'C', 'B'}))  # True

print(set_contains({('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')},
                   {'A', 'C', 'D'}))  # False

It may be possible to reduce on the amount of sorting, depending on how exactly combinations works (I'm not 100% sure what to make of the docs) and if you reuse either foo or var several times and can thus sort one of the parts just once beforehand.

Upvotes: 2

lpiner
lpiner

Reputation: 465

This is not as 'compact' as the others but works the same.

for x in var:
    for y in foo:
        if x in y:
            print('Found %s in %s' % (x, y))
        else:
            print('%s not in %s' % (x, y))

B not in ('C', 'D')
B not in ('A', 'C')
Found B in ('A', 'B')
Found B in ('B', 'C')
A not in ('C', 'D')
Found A in ('A', 'C')
Found A in ('A', 'B')
A not in ('B', 'C')
Found C in ('C', 'D')
Found C in ('A', 'C')
C not in ('A', 'B')
Found C in ('B', 'C')

Upvotes: 0

Mattia
Mattia

Reputation: 11

Try this:

foo = {('A', 'B'), ('C', 'D'), ('B', 'C'), ('A', 'C')}
var = {'A', 'C', 'B'}

for elem in var:
    if any(elem in tuples for tuples in foo):
        print(True)

Upvotes: 0

Related Questions