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

鍍金池/ 問答/Python/ Python 全排列中的局部變量問題

Python 全排列中的局部變量問題

一個全排列的問題

def permute(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    ans=[]
    flag={}
    l = len(nums)
    for j in range(l):
        flag[j]=False
    def bt(tmp=[],flag=flag):
        if len(tmp) == l:
            print(tmp)
            ans.append(tmp)
        for i in range(l):
            if flag[i] == False:
                flag[i]=True
                tmp.append(nums[i])
                print(tmp)
                bt(tmp,flag)
                flag[i]=False
                tmp.pop()
    bt()
    return ans

    
if __name__ == '__main__':
    c=[1,2,3]
    res=permute(c)
    print(res) 

現(xiàn)在返回值為[[], [], [], [], [], []]
感到不解,,現(xiàn)在發(fā)現(xiàn)問題在tmp這個變量上,但是不知道為什么,請大佬解答,,謝謝!

回答
編輯回答
情皺

ans.append(tmp) 換成 ans.append([i for i in tmp])
或者換成 ans.append(copy.copy(tmp))

解釋:
你一直在對同一個 list 操作,如

a = [1,2,3]
b = a
b.pop()
a  # [1,2]
b  # [1,2]
c = copy.copy(a)
c.pop()
a  # [1, 2]
c  # [1]

還有,要避免 可變數(shù)據(jù)類型作為函數(shù)定義中的默認參數(shù),比如你上面的:

def bt(tmp=[], flag=flag)

最好不要這么寫,雖然并不影響你的結果,參考:
http://www.pythontab.com/html...

2018年5月11日 01:00