Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a word into all possible 'subwords' - All possible combinations

Tags:

python

I am trying to split 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 covered all possbile ways to arrange 'Bang'. I thought long about it but could not find a way.

list(permutations('Bang', 3))

Permutations method does not return the entire word. I can split into 2 words but unable to split a word into 3 or more(for a bigger word).

Splitting into 2 words can be done using the below code which was suggested by one of the members.

[ [word[:i],word[i:]] for i in range(1,len(word))]
like image 766
Aman Avatar asked Apr 05 '17 22:04

Aman


1 Answers

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')
like image 108
Kenan Banks Avatar answered Oct 25 '22 11:10

Kenan Banks