【发布时间】:2022-01-27 02:51:33
【问题描述】:
我被分配了一个使用递归的任务,以便任何给它的列表都说 p 将在所需的输出中返回,如最后所示,而不会干扰或改变 p 的内容。当我运行这个函数时,它说局部变量 (y) 是在没有赋值的情况下引用的,即 len(y)==0 但我已经在函数 init 之外分配了 y。有人可以帮助找出问题所在吗?
y=[] #To copy contents of x in it so that x is not modified
z=[] # To return it as a list required in the question
p=[1,2,3]
def inits(x):
if len(y)==0 and len(z)==0:
y=[i.copy for i in x] #Copying contents of x into x so that it remains unchanged
if len(z)==len(x)+1: #z list is one plus x list because it has [] in it
print(z)
else:
z.append(y.copy())
if len(y)!=0: #This is done so that when y=[] it does not return error for y.pop(-1)
y.pop(-1)
inits(x)
inits(p)
#Desired Output
[[1,2,3],[1,2],[1],[]]
【问题讨论】:
标签: python-3.x list recursion