![](/img/trans.png)
[英]Python's implementation of Permutation Test with permutation number as input
[英]Permutation implementation
permutation_str 工作正常,但 permutation_arr 沒有輸出正確的答案。 鑒於它們具有相同的實現,我不明白為什么這兩個函數會生成不同的輸出。 有什么我想念的嗎?
def permutation_arr(res, arr):
if len(arr) == 0:
print(res)
for i in range(len(arr)):
res.append(arr[i])
permutation_arr(res, arr[:i] + arr[i+1:])
res = res[:-1]
permutation_arr([], [1,2,3])
def permutation_str(res, str):
if len(str) == 0:
print(res)
for i in range(len(str)):
res = res + str[i]
permutation_str(res, str[:i] + str[i+1:])
res = res[:-1]
permutation_str("", "123")
數組是可變的......所以你不斷追加的 res 總是相同的
試試這個
def permutation_arr(res, arr):
if len(arr) == 0:
print(res)
for i in range(len(arr)):
res.append(arr[i])
# send a copy of res instead of res
permutation_arr(res[:], arr[:i] + arr[i+1:])
res = res[:-1]
permutation_arr([], [1,2,3])
正確的做法是在完成遞歸調用后使用pop
刪除最后一個元素。 不要再次創建副本。 pop
不會拋出空列表異常,因為您是在append
之后執行的。 res[:-1] 創建了一個不同的列表,並且您不想在遞歸調用中傳遞時更改列表,您希望在遞歸中傳遞相同的列表。
def permutation_arr(res, arr):
if len(arr) == 0:
print(res)
for i in range(len(arr)):
res.append(arr[i])
permutation_arr(res, arr[:i] + arr[i+1:])
res.pop()
permutation_arr([], [1,2,3])
輸出:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.