DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Generate All Permutation Of A List

09.20.2005
| 52542 views |
  • submit to reddit
        From Michael Davies's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252178>recipe</a>.
def all_perms(str):
    if len(str) <=1:
        yield str
    else:
        for perm in all_perms(str[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + str[0:1] + perm[i:]
Some example usage
>>> for p in all_perms(['a','b','c']):
	print p

['a', 'b', 'c']
['b', 'a', 'c']
['b', 'c', 'a']
['a', 'c', 'b']
['c', 'a', 'b']
['c', 'b', 'a']
A great use of generator and recursive call.    

Comments

Snippets Manager replied on Mon, 2006/03/06 - 3:54am

Thanks, that's just what I was looking for