2019-07-16 18:51:07 +02:00
|
|
|
from lib_misc import permutations
|
2019-07-16 04:11:49 +02:00
|
|
|
|
|
|
|
|
|
|
|
def euler_024_library():
|
2019-07-16 18:51:07 +02:00
|
|
|
from itertools import permutations
|
2019-07-16 04:11:49 +02:00
|
|
|
return int("".join(list(permutations("0123456789"))[1000000 - 1]))
|
|
|
|
|
|
|
|
|
2019-07-16 18:51:07 +02:00
|
|
|
def nth(generator, n):
|
2019-07-16 04:11:49 +02:00
|
|
|
for i in range(n):
|
|
|
|
next(generator)
|
|
|
|
return next(generator)
|
|
|
|
|
|
|
|
|
2019-07-16 18:51:07 +02:00
|
|
|
def nth_permutation(iterable, n):
|
|
|
|
""" Returns the nth permutation of the iterable. """
|
2019-07-16 19:43:08 +02:00
|
|
|
|
|
|
|
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)
|
2019-07-16 18:51:07 +02:00
|
|
|
|
|
|
|
|
2019-07-16 04:11:49 +02:00
|
|
|
def euler_024():
|
2019-07-16 19:43:08 +02:00
|
|
|
""" 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))
|
2019-07-16 04:11:49 +02:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
print("e024.py: {}".format(euler_024()))
|
|
|
|
assert(euler_024() == 2783915460)
|