1

When using recursion in python3 let's say I have a function 'f(a,b)'.('b' is list) And within 'f' I am calling 'f' several times recursively. If a daughter instance of 'f' makes some changes to list 'b' how do I avoid those changes in 'b' to be reflected in the calling parent f? (I am not returning 'b'). For e.g. have a look at my code below. In the second elif I am making two recursive calls to the function goToDepth. If one of the called instance makes a change to depthArr , the change is being reflected in the calling function's copy of depthArr as well which I don't want. How to avoid that? Thanks a lot in advance!

def goToDepth(headNode,depthArr):
    if(headNode==None):
        return
    elif(not depthArr):
        return
    elif(depthArr[-1]!=1):
        depthArr[-1]=depthArr[-1]-1
        goToDepth(headNode.left,depthArr)
        goToDepth(headNode.right,depthArr)
    elif (depthArr[-1]==1):    
        headNode.left,headNode.right=headNode.right,headNode.left
        depthArr.pop()
        goToDepth(headNode.left,depthArr)
        goToDepth(headNode.right,depthArr)
    else:
        return
0

1 Answer 1

1

Try passing copies of your list: a[:] creates a shallow copy.

Use the copy module to create deep copies (but that's probably bad design).

Sign up to request clarification or add additional context in comments.

Comments

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.