Created
February 23, 2012 06:06
-
-
Save nskeip/1890955 to your computer and use it in GitHub Desktop.
Permutations algorythm implementation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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