Erik
Erik

Reputation: 305

Compute all powerset intersections of two lists

I found many articles about finding intersection of 2 lists, but in none of them was written how could I get all intersections (maybe it could be called subintersections).

Example:

list1 = ['a', 'b', 'c', 'd']
list2 = ['b', 'c', 'd', 'e']

print (find_all_intersections(list1, list2))

Output:

['b', 'c', 'd', 'bc', 'bd', 'cd', 'bcd']

Is there any function which can make this?

Upvotes: 2

Views: 326

Answers (1)

cs95
cs95

Reputation: 402603

Well, it's actually pretty simple. Once you've found the intersection, compute the powerset:

from itertools import chain, combinations

s = set(list1).intersection(list2)
[''.join(c) for c in chain.from_iterable(
    combinations(s, r) for r in range(len(s)+1)) if c]

['b', 'c', 'd', 'bc', 'bd', 'cd', 'bcd']

More information on generating powersets can be found here.

Upvotes: 4

Related Questions