Python以递归方式返回n个列表的出现,无需切片/深度复制或内置函数

Posted

技术标签:

【中文标题】Python以递归方式返回n个列表的出现,无需切片/深度复制或内置函数【英文标题】:Python return occurrence of n lists recursively without slicing / deepcopy or inbuilt functions 【发布时间】:2022-01-06 15:31:15 【问题描述】:

您不能使用内置函数或切片或深拷贝或复制,或 while 或 for

假设这是我们的函数:

def list_occur(n):

它以 n 作为 int 参数输入,并返回一个大小为 n 的列表,显示该系列中的元素 n(输出):

n = 0: returns []
n = 1: returns list with size 1 that takes in index=0 [], means returns [ [] ]
n = 2: returns list with size 2 that takes in index=0 [] and index = 1 [ [] ], means returns:
[ [], [ [] ] ]
n = 3: returns list with size 3 that takes in index=0 [], index =1 [ [] ], index = 2 [ [], [ [] ] ] 
means its returns [ [], [ [] ], [ [], [ [] ] ] ]

我尝试解决这个问题,但是当我尝试 n = 2 + 时出现错误“AttributeError: 'NoneType' object has no attribute 'append' :

  def occur(n) :

    return occr_helper(n)



def occr_helper(n) :

    if (n == 0):
        return []

    return occr_helper(n-1).append(occr_helper(n-1))

    if __name__ == "__main__":

    print(occur(1))

【问题讨论】:

empty_list.append([]) 返回无。您将 None 传递给您的递归调用。 感谢您的通知,我会尝试再次解决问题,因为它似乎是错误的,有什么方向吗? @khelwood 【参考方案1】:

对于此函数,n+1 返回附加到nn。这可以很容易地递归编码:

num = 3

def occr(n):
    if n == 0:
        return []
    else:
        new_l = occr(n-1)
        new_l.append(occr(n-1))
        return new_l

print(occr(num))

【讨论】:

你的方法工作正常,我再次编辑了我的代码,但我仍然有 None Type 的错误,你能解释一下为什么你的方法有效而我没有? @SchevenzRs list.append 函数将始终返回 None。这就是为什么我需要两行而不是一行 return new_l.append(occr(n-1))new_l.append(occr(n-1))return new_l 很好地观察到n+1n 附加到n!但是,您可以通过将 else 块替换为 new_l = occr(n-1); return new_l + [new_l] 来大大提高速度

以上是关于Python以递归方式返回n个列表的出现,无需切片/深度复制或内置函数的主要内容,如果未能解决你的问题,请参考以下文章

菜鸟学飞之Python递归切片迭代

递归比较两个列表

以4个项目的切片分页python列表[重复]

python之内置函数与匿名函数递归函数初识

python怎么将列表中元素分配成三份(无需连续),列举出所有的方案?

Python列表赋值