I know how to get the permutations of just the plain string in python:
>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> print perms
...
But how would I get the permutations of 'stac'
, 'stak'
, 'sack'
, 'stck'
, 'stc'
, 'st'
, and so forth? My desired output is:
>>> permutations('pet')
['pet', 'pte', 'ept', 'etp', 'tpe', 'tep', 'pe', 'ep', 'p', 'e', 't', 'pt', 'tp', 'et', 'te']
What I have so far:
def permutate(values, size):
return map(lambda p: [values[i] for i in p], permutate_positions(len(values), size))
def permutate_positions(n, size):
if (n==1):
return [[n]]
unique = []
for p in map(lambda perm: perm[:size], [ p[:i-1] + [n-1] + p[i-1:] for p in permutate_positions(n-1, size) for i in range(1, n+1) ]):
if p not in unique:
unique.append(p)
return unique
def perm(word):
all = []
for k in range(1, len(word)+1):
all.append(permutate([' ']+list(word), k))
return all
This runs as:
>>> perm('pet')
[[['t'], ['e'], ['p']], [['t', 'e'], ['e', 't'], ['e', 'p'], ['t', 'p'], ['p', 't'], ['p', 'e'], ['p', 'p']], [['t', 'e', 'p'], ['e', 't', 'p'], ['e', 'p', 't'], ['e', 'p', 'p'], ['t', 'p', 'e'], ['p', 't', 'e'], ['p', 'e', 't'], ['p', 'e', 'p'], ['t', 'p', 'p'], ['p', 't', 'p'], ['p', 'p', 't'], ['p', 'p', 'e']]]
>>>
However, it has a bunch of list of lists, and with values like ['p', 'p', 't']!
How do I do this? ANy help is appreciated.
This is one way of doing it with itertools.permutations:
from itertools import permutations
s = 'pet'
print [''.join(p) for i in range(1, len(s)+1) for p in permutations(s, i)]
Output:
['p', 'e', 't', 'pe', 'pt', 'ep', 'et', 'tp', 'te', 'pet', 'pte', 'ept', 'etp', 'tpe', 'tep']
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