Over a million developers have joined DZone.

Generate All Permutation Of A List

DZone's Guide to

Generate All Permutation Of A List

· ·
Free Resource
From Michael Davies's recipe.

def all_perms(str):
    if len(str) <=1:
        yield str
        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.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}