2017-06-05 58 views
1

我試圖獲得所有可能的骰子組合排列。以下是我的代碼。AttributeError:'NoneType'對象沒有屬性'append'(遞歸函數)

def PrintAllPerms(n, arr, str_): 
    if (n == 0): 
     print str_ 
     arr.append(str_) 
     return arr 
    else: 
     for i in ["1","2","3","4","5","6"]: 
      str_ = str_ + i 
      arr = PrintAllPerms(n-1,arr,str_) 
      str_ = str_[:-1] 

PrintAllPerms(2,[],"") 

但是打印後只有這麼多,我得到以下錯誤。

PrintAllPerms(2,[],"") 

11 
12 
13 
14 
15 
16 
21 

<ipython-input-7-d03e70079ce2> in PrintAllPerms(n, arr, str_) 
     2  if (n == 0): 
     3   print str_ 
----> 4   arr.append(str_) 
     5   return arr 
     6  else: 

AttributeError: 'NoneType' object has no attribute 'append' 

爲什麼直到2,1打印呢?

什麼是正確的方式來解決這個問題?

回答

2

您需要在else分支中返回arr

def PrintAllPerms(n, arr = [], str_ = ''): 
    if n == 0: 
     print(str_) 
     arr.append(str_) 
     return arr 
    else: 
     for i in ['1','2','3','4','5','6']: 
      str_ = str_ + i 
      arr = PrintAllPerms(n-1,arr,str_) 
      str_ = str_[:-1] 
     return arr 

PrintAllPerms(2) 
3

這是由於以下行:

arr = PrintAllPerms(n-1,arr,str_) 

,如果它需要的else路徑,因此,如果是返回None對待你PrintAllPerms函數不返回任何東西。所以arr被設置爲None