Mitya Stiglitz
Mitya Stiglitz

Reputation: 87

Using a tuple (i,j,k,...) to construct an intersection list_of_sets[i] & list_of_sets[j] & list_of_sets[k]

I am searching through a tree. At each node, I need to find an intersection of some combination of sets, which are all contained in list_of_sets=[set_1,set_2,...,set_n].

I use a tuple of indexes to keep track of which node I am in, i.e. node=[i,j,k,...]. The size of this tuple varies from 1 to 5 depending on the position in the tree.

At any node, e.g. node=[i,j,k,l], I would like to construct such an expression:

intersection = list_of_sets[i] & list_of_sets[j] & list_of_sets[k] & list_of_sets[l]

I have absolutely no clue how get started on this one. Your advice is deeply appreciated ;)

Upvotes: 0

Views: 56

Answers (1)

vaultah
vaultah

Reputation: 46593

In [34]: sets, node = [{1, 4}, {4, 5}, {4, 10}], (0, 1, 2)

In [35]: set.intersection(*(sets[x] for x in node))
Out[35]: {4}

The above works because sets' intersection method accepts arbitrary number of sets for intersecting. You can also use operator.itemgetter:

In [38]: set.intersection(*itemgetter(*node)(sets))
Out[38]: {4}

Upvotes: 2

Related Questions