为什么在python列表(递归)上出现列表错误?

2024-06-16 10:29:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在列表中创建自定义排列(主要是为了在python中处理递归)。现在我在运行代码时遇到以下错误:

TypeError: 'NoneType' object is not iterable

在我将复制添加到列表中之前,我得到的是:

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

def findPermutations (size, max, curr_perm):
    if not curr_perm or len(curr_perm) < size:
        for i in range(1,max):
            new_arr = list(curr_perm)
            findPermutations(size, max, new_arr.append(i))
    else:
        return curr_perm


print(findPermutations(2,3,[]))

我希望能换回一串或排列。我做错什么了?你知道吗


Tags: 代码列表newsizeobject错误notmax
2条回答

要解决您的代码:

    new_arr.append(i)
    findPermutations(size, max, new_arr)

在调用递归函数之前,需要追加项列表。下面是工作代码,请让我知道如果你有任何问题,我将非常乐意帮助你。你知道吗

def findPermutations (size, max, curr_perm):
    if not curr_perm or len(curr_perm) < size:
        for i in range(1,max):
            new_arr = list(curr_perm)
            new_arr.append(i)
            print(new_arr)
            findPermutations(size, max, new_arr)
    else:
        return curr_perm
findPermutations(2,3,[])
**Result:**
[1]
[1, 1]
[1, 2]
[2]
[2, 1]
[2, 2]

相关问题 更多 >