鍍金池/ 問答/Python/ 關于python全排列問題

關于python全排列問題

def permutations(a):
    result = []
    helper(a, result, 0, len(a))
    return result


def helper(a, result, lo, hi):
    if lo == hi:
        print(a)
        result.append(a)
    else:
        cursor = lo
        for i in range(lo, hi):
            a[cursor], a[i] = a[i], a[cursor]
            helper(a, result, lo + 1, hi)
            a[cursor], a[i] = a[i], a[cursor]


if __name__ == '__main__':
    a = [1, 2, 3]
    re = permutations(a)
    print(re)

輸出:

clipboard.png

實在想不通,為什么result中的值全是[1,2,3]

回答
編輯回答
心癌

另外說一下,Python自帶有排列組合函數(shù)

from itertools import combinations  # 組合
from itertools import combinations_with_replacement  # 組合(包含自身)
from itertools import product  # 笛卡爾積
from itertools import permutations  # 排列
2018年3月2日 20:22
編輯回答
傲寒

因為操作的是同一個對象,保存結果時應該生成一個新對象,像這樣

        # result.append(a)
        result.append(tuple(a))
2017年6月28日 21:34