There is a related question here. I am attempting to do this project Euler challenge on HackerRank. What it requires is that you are able to derive the nth permutation of a string "abcdefghijklm". There are 13! permutations.
I tried a simple solution where I used for num, stry in zip(range(1, math.factorial(13)), itertools.permutations("abcdefghijklm"):
. That works, but it times out.
What would be really nice is to store each value in a dict
as I go along, and do something like this:
import itertools
import math
strt = "abcdefghijklm"
dic = {}
perms_gen = itertools.permutations(strt)
idxs_gen = range(1, math.factorial(13))
curr_idx = 0
test_list = [1, 2, 5, 10]
def get_elems(n):
for num, stry in zip(idxs_gen, perms_gen):
print(num) # debug
str_stry = "".join(stry)
dic[num] = str_stry
if num == n:
return str_stry
for x in test_list:
if curr_idx < x:
print(get_elems(x))
else:
print(dic[x])
This doesn't work. I get this output instead:
1
abcdefghijklm
1
2
abcdefghijlkm
1
2
3
4
5
abcdefghikjml
1
2
3
4
5
6
7
8
9
10
abcdefghilmkj
As I was writing this question, I apparently found the answer... to be continued.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…