Python return n 个列表递归出现,没有切片/深度复制或内置函数
Python return occurrence of n lists recursively without slicing / deepcopy or inbuilt functions
您不能使用内置函数或切片或深层复制或复制,或 while 或 for
假设这是我们的函数:
def list_occur(n):
它将 n 作为 int 参数输入和 returns 一个大小为 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))
为此函数 n+1
returns n
附加到 n
。这可以很容易地递归编码:
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))
您不能使用内置函数或切片或深层复制或复制,或 while 或 for
假设这是我们的函数:
def list_occur(n):
它将 n 作为 int 参数输入和 returns 一个大小为 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))
为此函数 n+1
returns n
附加到 n
。这可以很容易地递归编码:
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))