Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 属性错误:';非类型';对象没有属性';追加';(递归函数)_Python_List_Recursion_Append_Python 2.x - Fatal编程技术网

Python 属性错误:';非类型';对象没有属性';追加';(递归函数)

Python 属性错误:';非类型';对象没有属性';追加';(递归函数),python,list,recursion,append,python-2.x,Python,List,Recursion,Append,Python 2.x,我正在尝试所有可能的骰子排列。下面是我的代码 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(

我正在尝试所有可能的骰子排列。下面是我的代码

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'
PrintAllPerms(2,[],“”)
11
12
13
14
15
16
21
在PrintAllPerms中(n,arr,str_u)
2如果(n==0):
3打印str_
---->4 arr.append(str_u)
5返回arr
6其他:
AttributeError:“非类型”对象没有属性“附加”
为什么打印到2,1呢


处理这个问题的正确方法是什么?

这是由于以下几行:

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

如果
PrintAllPerms
函数采用
else
路径,则它不会返回任何内容,因此被视为返回
None
。因此
arr
设置为
None

这是由于以下行:

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

如果
PrintAllPerms
函数采用
else
路径,则它不会返回任何内容,因此被视为返回
None
。因此
arr
设置为
None

您需要在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)

您需要在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)