Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get every single permutation of all substrings of a string?

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.

like image 624
A.J. Uppal Avatar asked Feb 14 '23 04:02

A.J. Uppal


1 Answers

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']
like image 105
YS-L Avatar answered Feb 15 '23 19:02

YS-L