外層函式的變數直接被巢狀函式引用計算

程式碼女民工發表於2021-11-03

fun1()函式中的b在fun2()中直接用
class Solution:  

 def fun1(self,a,b):
        c = a + b
        b = 0         
        def fun2(c):
            b += 1      #報錯:UnboundLocalError: local variable 'b' referenced before assignment
            print('b=',b)
            print('c=',c)
            return
        
        fun2(c)
        print(b)
        return 0
   
result = Solution()
result.fun1(1,2)

示例2:但是下邊程式中Permutation(self, ss)中的lens變數卻能直接在dfs函式中使用,這是為什麼?
class Solution:   
    def Permutation(self, ss):  
        lens = len(ss)    #該變數具有全域性性,在dfs中可以直接用。
        box = [0] * lens  
        book =[0] * lens  
        steps = 0     
        ans = []           
        if len(ss) == 0:  
            return []
        def dfs(steps):
            if steps > lens-1:    #重點:Permutation的變數lens可以直接在dfs中應用
                str1 = ''        
                for j in range(lens):  
                    #print("{0}".format(box[j]),end='')
                #print('\n')
                    str1 = str1 + box[j]   
                ans.append(str1)
               
                return
            
            for i in range(lens):      
                if book[i] == 0 :   
                    box[steps] = ss[i]
                    book[i] = 1      

                    dfs(steps + 1)   #遞迴
                    book[i] = 0  
            return
            
        dfs(steps)  #函式中若要呼叫巢狀函式,需要引用這個函式
        
        #在dfs及自身的遞迴結束後,輸出列表ans
        #特殊情況2:ss=['a','a'],有重複的字母時,要用去重
        ans = list(set(ans))   #去重:set去重後返回的是set型別,要改為list型別
        ans = sorted(ans)      #再對ans結果排序,從小到大
        print(ans)
        return ans
        
        
ss = ['a','b','c']
result = Solution()
result.Permutation(ss)  

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/70007056/viewspace-2840484/,如需轉載,請註明出處,否則將追究法律責任。

相關文章