Welcome, guest | Sign In | My Account | Store | Cart

This will give a result that is more than a permutation, but all possible combinations. An example is when input is 'abc', the output would be: a,ab,abc,ac,acb,b,ba,bac,bc,bca,c,ca,cab,cb,cba

Python, 5 lines
1
2
3
4
5
def allperm(inputstr):
    for i in range(len(inputstr)):
        yield(inputstr[i])        
        for s in allperm(inputstr[:i] + inputstr[i+1:]):
            yield(inputstr[i] + s)

5 comments

Ori Livneh 12 years, 8 months ago  # | flag

from itertools import permutations [perm for length in range(1, len(inputstr) + 1) for perm in permutations(inputstr, length)]

Yang (author) 12 years, 8 months ago  # | flag

oh, seems like i just re-invented the wheel:(

Thanks Ori for the hint,and good job rhettinger ;)

victor chung 12 years, 8 months ago  # | flag

The author's recipe is easier to understand than the 'from itertools import permutations' way.

Lorenzo Bolognini 12 years, 7 months ago  # | flag
import sys
from itertools import permutations 

inputstr = sys.argv[1].upper()
print inputstr

perms = (p for p in permutations(inputstr))
for p in perms:
    print ''.join(p)
Joe Porter 11 years, 5 months ago  # | flag

Nice recipe. This site helped explain it in detail:

Find all permutations of a string

Created by Yang on Mon, 15 Aug 2011 (MIT)
Python recipes (4591)
Yang's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks