Separation of a word into all possible "subwords" - all possible combinations

I try to break a word into subwords - all possible permutations.

Input: Bang
Output: [['B','ang'], ['Ba','ng'], ['Ban','g'], ['B','a','ng'], ['B','an','g'], ['Ba','n','g'], ['B','a','n','g']]

I hope I’ve covered all the possible ways to make a Bang. I thought about this for a long time, but could not find a way.

list(permutations('Bang', 3))

The permutation method does not return the whole word. I can divide into 2 words, but I can not divide a word into 3 or more (for a larger word).

The 2 word division can be done using the code below, which was suggested by one of the members.

[ [word[:i],word[i:]] for i in range(1,len(word))]
+4
source share
1 answer

Here ya go ..

def combos(s):
  if not s:
    return
  yield (s,)
  for i in range(1, len(s)):
    for c in combos(s[i:]):
      yield (s[:i],) + c

for c in combos('Bang'):
  print c

Output:

('Bang',)
('B', 'ang')
('B', 'a', 'ng')
('B', 'a', 'n', 'g')
('B', 'an', 'g')
('Ba', 'ng')
('Ba', 'n', 'g')
('Ban', 'g')
+2
source

Source: https://habr.com/ru/post/1674146/


All Articles