在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 關(guān)于python全排列問題

關(guān)于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

實(shí)在想不通,為什么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
編輯回答
傲寒

因?yàn)椴僮鞯氖峭粋€(gè)對象,保存結(jié)果時(shí)應(yīng)該生成一個(gè)新對象,像這樣

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