Implemented nth permutation function.
parent
d94fc90600
commit
de21284672
|
@ -14,13 +14,31 @@ def nth(generator, n):
|
|||
|
||||
def nth_permutation(iterable, n):
|
||||
""" Returns the nth permutation of the iterable. """
|
||||
# XXX: Implement this!
|
||||
return 0
|
||||
|
||||
def iterate_permutations(accumulator, iterable, count=[0]):
|
||||
if not iterable:
|
||||
if count[0] == n:
|
||||
return accumulator
|
||||
count[0] += 1
|
||||
return False
|
||||
for i in range(len(iterable)):
|
||||
elem = iterable[i:i + 1]
|
||||
rest = iterable[:i] + iterable[i + 1:]
|
||||
p = iterate_permutations(accumulator + elem, rest)
|
||||
if p:
|
||||
return p
|
||||
return False
|
||||
|
||||
return iterate_permutations([], iterable)
|
||||
|
||||
|
||||
def euler_024():
|
||||
g = permutations("0123456789")
|
||||
return int(nth(g, 1000000 - 1))
|
||||
""" My first solution used a generator to get all permutations till
|
||||
the desired one. My improved solution uses a function that returns only
|
||||
the nth iteration which is the same algorithm, but does not required to
|
||||
return all the permutations that are discarded anyway. """
|
||||
return int("".join(nth_permutation(list("0123456789"), 1000000 - 1)))
|
||||
# return int(nth(permutations("0123456789"), 1000000 - 1))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
def euler_036():
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("e036.py: {}".format(euler_036()))
|
||||
assert(euler_036() == 55)
|
Loading…
Reference in New Issue