How to get each permutation of a line?

I know how to get simple string permutations in python:

>>> from itertools import permutations
>>> perms = [''.join(p) for p in permutations('stack')]
>>> print perms
...

But how to get the permutation 'stac', 'stak', 'sack', 'stck', 'stc', 'st'and so on? My desired result:

>>> permutations('pet')
['pet', 'pte', 'ept', 'etp', 'tpe', 'tep', 'pe', 'ep', 'p', 'e', 't', 'pt', 'tp', 'et', 'te']

What I still have:

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 does have a list of lists with values ​​such as ['p', 'p', 't']!

How should I do it? Any help is appreciated.

+4
source share
1 answer

This is one way to do this 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)]

Conclusion:

['p', 'e', 't', 'pe', 'pt', 'ep', 'et', 'tp', 'te', 'pet', 'pte', 'ept', 'etp', 'tpe', 'tep']
+8
source

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


All Articles