2

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?

cs95
  • 379,657
  • 97
  • 704
  • 746
Erik
  • 303
  • 1
  • 3
  • 12

1 Answers1

4

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.

cs95
  • 379,657
  • 97
  • 704
  • 746