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))]
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With