我在https://www.hackerrank.com/challenges/itertools-permutations/problem上解决Hackerrank上的itertools.permutations()代码,我想出了以下非常简单的代码:
from itertools import permutations
to_perm, length = raw_input().split()
length = int(length)
res = permutations(to_perm, length)
new_res = []
for i in res:
new_res = sorted(res)
for i in new_res:
print "".join(i)这是我得到的输出:
AC
AH
AK
CA
CH
CK
HC
HK
KA
KC
KH这是我的预期输出:
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH你会注意到我遗漏了'HA‘这个排列。
我的问题是:为什么我错过了这个单一的排列?我该如何解决这个问题呢?
发布于 2019-03-08 18:29:18
我不确定在你的代码中HA会发生什么。下面的代码输出正确的结果:
from itertools import permutations
to_perm, length = 'HACK', 2
res = permutations(to_perm, length)
res = sorted(res)
for perm in res:
print ''.join(perm)输出
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KHhttps://stackoverflow.com/questions/55026485
复制相似问题