from lib_misc import permutations def euler_024_library(): from itertools import permutations return int("".join(list(permutations("0123456789"))[1000000 - 1])) def nth(generator, n): for i in range(n): next(generator) return next(generator) def nth_permutation(iterable, n): """ Returns the nth permutation of the iterable. """ 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(): """ 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__": print("e024.py: {}".format(euler_024())) assert(euler_024() == 2783915460)