Skip to content

Instantly share code, notes, and snippets.

@fbrosser
Created December 27, 2011 17:27
Show Gist options
  • Save fbrosser/1524467 to your computer and use it in GitHub Desktop.
Save fbrosser/1524467 to your computer and use it in GitHub Desktop.
Euler24
from Mathstuff import mathstuff
M = mathstuff()
A = M.permutations(range(9))
print A(10**6-1)
def permutations(self, iterable):
return list(set(self.doPermutations(iterable)))
def doPermutations(self, iterable, r=None):
pool = tuple(iterable)
n = len(pool)
if(r is None):
r = n
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