From de2128467215c79276451a3e3a8384b716cbb859 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Tue, 16 Jul 2019 13:43:08 -0400 Subject: [PATCH] Implemented nth permutation function. --- python/e024.py | 26 ++++++++++++++++++++++---- python/e036.py | 7 +++++++ 2 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 python/e036.py diff --git a/python/e024.py b/python/e024.py index 4596989..852517d 100644 --- a/python/e024.py +++ b/python/e024.py @@ -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__": diff --git a/python/e036.py b/python/e036.py new file mode 100644 index 0000000..f707850 --- /dev/null +++ b/python/e036.py @@ -0,0 +1,7 @@ +def euler_036(): + return 0 + + +if __name__ == "__main__": + print("e036.py: {}".format(euler_036())) + assert(euler_036() == 55)