Skip to content

Instantly share code, notes, and snippets.

@robert-wallis
Created September 22, 2011 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robert-wallis/1235148 to your computer and use it in GitHub Desktop.
Save robert-wallis/1235148 to your computer and use it in GitHub Desktop.
Permutations in Python (from Python website)
// directly from http://docs.python.org/library/itertools.html
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment