使用itertools.permutations()缺少排列

时间:2019-03-06 15:20:31

标签: python-2.7 permutation itertools

我在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'。

我的问题是:为什么我会错过这个单一排列?我该如何解决呢?

1 个答案:

答案 0 :(得分:0)

我不确定您的代码中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
KH