Implemented nth permutation function.
This commit is contained in:
@@ -14,13 +14,31 @@ def nth(generator, n):
|
|||||||
|
|
||||||
def nth_permutation(iterable, n):
|
def nth_permutation(iterable, n):
|
||||||
""" Returns the nth permutation of the iterable. """
|
""" 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():
|
def euler_024():
|
||||||
g = permutations("0123456789")
|
""" My first solution used a generator to get all permutations till
|
||||||
return int(nth(g, 1000000 - 1))
|
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__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
7
python/e036.py
Normal file
7
python/e036.py
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
def euler_036():
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("e036.py: {}".format(euler_036()))
|
||||||
|
assert(euler_036() == 55)
|
||||||
Reference in New Issue
Block a user