【发布时间】:2019-05-14 07:45:21
【问题描述】:
有一个相关的问题here。我正在尝试在 HackerRank 上进行 this project Euler 挑战。它需要的是您能够导出字符串“abcdefghijklm”的第 n 个排列。有13个!排列。
我尝试了一个简单的解决方案,我使用了for num, stry in zip(range(1, math.factorial(13)), itertools.permutations("abcdefghijklm"):。这行得通,但它会超时。
真正好的是将每个值存储在dict 中,然后执行以下操作:
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])
这不起作用。我得到了这个输出:
1
abcdefghijklm
1
2
abcdefghijlkm
1
2
3
4
5
abcdefghikjml
1
2
3
4
5
6
7
8
9
10
abcdefghilmkj
在我写这个问题的时候,我显然找到了答案……待续。
【问题讨论】:
-
哪个版本的 Python?在 Python 2 中,zip 返回一个列表。在 Python 3 中,zip 是一个类似于 itertools.izip 的迭代器,map 也类似于 itertools.imap。
-
@DanD。 Python 3。我认为这从代码中很明显?
标签: python python-3.x iteration generator