1

I encounter a problem in Python: Given a list of n elements, I would like to find all the "connected" element combination in the list. For example, given list = ['a', 'b', 'c'], I would like to find

['a', 'b', 'c']
['ab', 'c']
['a', 'bc']
['abc']

Similarly, given list = ['a', 'b', 'c', 'd'], I would like to find

['a', 'b', 'c', 'd']
['a', 'bc', 'd']
['a', 'b', 'cd']
['a', 'bcd']
['ab', 'c','d']
['ab', 'cd']
['abc', 'd']
['abcd']

Given a list of n elements, there will be 2^(n-1) combinations. May I ask whether there is any hint to help me with this? Shall I use recursion?

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • 1
    Does this answer your question? [Find all list permutations of splitting a string in Python](https://stackoverflow.com/questions/4904430/find-all-list-permutations-of-splitting-a-string-in-python) – Tomerikoo Feb 02 '21 at 15:37
  • @Tomerikoo Yes! This also solves my problem. Thanks a lot! :) – heathersherry Feb 03 '21 at 09:53

1 Answers1

5

Recursion is often the easiest to implement. Here is a generator function that would achieve this:

def connect(lst):
    if not lst:
        yield []
    for i in range(1, len(lst) + 1):
        prefix = ''.join(lst[:i])
        for suffix_con in connect(lst[i:]): 
            yield [prefix] + suffix_con

The approach takes any str.joined prefix of the list, and combines it with every set of connections recursively obtained from the respective suffix.

>>> list(connect(['a', 'b', 'c']))
[['a', 'b', 'c'], ['a', 'bc'], 
 ['ab', 'c'], 
 ['abc']]
>>> list(connect(['a', 'b', 'c', 'd']))
[['a', 'b', 'c', 'd'], ['a', 'b', 'cd'], ['a', 'bc', 'd'], ['a', 'bcd'], 
 ['ab', 'c', 'd'], ['ab', 'cd'], 
 ['abc', 'd'], 
 ['abcd']]
user2390182
  • 72,016
  • 6
  • 67
  • 89