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']]
Asked
Active
Viewed 133 times
0
-
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 Answers
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
-
1Please update your answer with an explanation of *why* it works, no matter how trivial it may appear to you. – gmdev Mar 01 '22 at 13:40
-
1This works, I would replace `yield (start, end)` with `yield [start, end]` so every element is a list. – Matteo Zanoni Mar 01 '22 at 13:40
-
2Yes, explanation is always good, also don't use `str` as a variable name. – Eli Harold Mar 01 '22 at 13:40
-
1Perfect ! Thank you. I just change yield(start,end) to yield ([start, end]) to have list of lists. – axel584 Mar 01 '22 at 13:44
-
1