Skip to content

Instantly share code, notes, and snippets.

@nskeip
Created February 23, 2012 06:06
Show Gist options
  • Save nskeip/1890955 to your computer and use it in GitHub Desktop.
Save nskeip/1890955 to your computer and use it in GitHub Desktop.
Permutations algorythm implementation.
def permutations(l):
"""
>>> f = permutations
>>> f(['a', 'b'])
[('a', 'b'), ('b', 'a')]
>>> f(['a', 'b', 'c'])
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]
"""
if len(l) == 1:
return [(l[0],)]
else:
ret = []
for i, item in enumerate(l):
others = l[:i] + l[i + 1:]
for p in permutations(others):
ret.append((item,) + p)
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment