0
給定的字符串是''
。 我想生成其第一百萬個排列(1000000
)。使用itertools.permutation時計算排列的意外結果
我想給itertools.permutations
第一次嘗試:
In [85]: import itertools
In [86]: a = list(itertools.permutations(''))
In [87]: a[1]
Out[87]: ('0', '1', '2', '3', '4', '5', '6', '7', '9', '8')
In [88]: a[1000000]
Out[88]: ('2', '7', '8', '3', '9', '1', '5', '6', '0', '4')
但是如果我運行下面的代碼:
def perm(S, perms=[], current=[], maximum=None):
if maximum and len(perms) > maximum:
return
size = len(S)
for i in range(size):
subset = list(S)
del(subset[i])
tmp_current = list(current)
tmp_current.append(S[i])
if size > 1:
perm(subset, perms, tmp_current, maximum)
else:
perms.append(tmp_current)
if maximum:
if len(perms) == maximum:
print tmp_current
return
perm('', maximum=1000000)
# the result is ['2', '7', '8', '3', '9', '1', '5', '4', '6', '0']
從和itertools.permutations並從上面的僞代碼答案不匹配。
[2783915604] from itertools
[2783915460] from the snippet above
第二個答案是正確的答案。任何人都可以解釋一下爲什麼第一個過程沒有產生正確的結果?
我感覺其中一個選項是零索引(即第二個),而另一個是索引(第一個)。我不是Python的專家,但這似乎是問題所在。用0和1嘗試第二種方法。 – 2012-02-12 15:23:13