Home > database >  Using Recursion to get lists of original list in Python returns error
Using Recursion to get lists of original list in Python returns error

Time:12-29

I am given a task to use recursion so that any list that is given to it say p would be return in the desired output as shown at the end without disturbing or altering the contents of p. When I run this function it says that local variable (y) is referenced without assignment i.e. len(y)==0 but I have already assigned y outside the function init. Can someone help identify what's wrong?

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],[]]

CodePudding user response:

If you don't need the last empty element then feel free to remove the else block.
Your y variable is also not needed as for me

z = []  # To return it as a list required in the question

def foo(param):
    if len(param):
        z.append([i for i in param])
        foo(param[0:-1])
    else:
        z.append([])


foo([1, 2, 3])
print(z)

[[1, 2, 3], [1, 2], [1], []]
  • Related