1

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

1 Answer 1

2

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], []]
Sign up to request clarification or add additional context in comments.

2 Comments

Bravo, that's terrific but I'm still confused about my error python generated. I have assigned y and z outside function but it still gave error, why?
@AzhanAhmed Well, you had at least two errors: you had to use global y in your function and second i.copy a copy on integer also was wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.