0

I would like to split a string and have every sublist (in the same order) : ex. from 'ABC' => [['A','B','C'],['AB',C'],['A','BC']]

axel584
  • 235
  • 2
  • 9
  • Please clarify your question more But to split given str e.g. `word` to get list of chars -> `chars_ = split(word)`, and for permutations we can do `perms_ = itertools .permutations(chars_)` this will give you combinations of the input liit of chars. – ElSheikh Mar 01 '22 at 13:35
  • What would be the output for 'ABCD'? and 'ABCDE'? – mozway Mar 01 '22 at 13:37
  • @mozway can't speak for op, but I understood it would be `['A', 'BCD'], ['A', 'B', 'CD'], ['A', 'B', 'C', 'D'], ['A', 'BC', 'D'], ['AB', 'CD'],['AB', 'C', 'D'], ['ABC', 'D']` – Anass Mar 01 '22 at 13:45

1 Answers1

2
def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result

combinations = list(splitter(str))

Used a generator so used yield. If you do not want to use generator then use this -

def permute(s):
    result = [[s]]
    for i in range(1, len(s)):
        first = [s[:i]]
        rest = s[i:]
        for p in permute(rest):
            result.append(first + p)
    return result

Advantage of using generator - Memory efficient method of generating sequence types in python.

Edit: Explanation - Idea: permutation of string = set containing string itself, and a group of each substring X of string with the permutation of s\X. For example, permute('abc'):

{'abc'} # 'abc' itself
{'a', 'bc'} # substring 'a' group 1st permutation of 'bc' = {'b, 'c'}
{'a', 'b', 'c'} # substring 'a' grouped 2nd permutation of 'bc' = {'bc'}
{'ab', 'c'} # substring 'ab' add/group 1st and only permutation of 'c' = {'c'}
Innomight
  • 556
  • 3
  • 15