0

I have a question about how Python return value. Below is my simple python code practicing recursive function.

def brackets(ans, n, cur, open, close):
    if len(cur) == n*2:
        ans.append(cur)   # <---l.1
        return ans        # <---l.2   

    if open < n:
        brackets(ans, n,cur+"(",open+1,close)

    if open > close:
        brackets(ans, n,cur+")",open,close+1)

ans = []
ret = brackets(ans, 2, "", 0,0)  # <---l.3
print(ans)
print(ret)

===== 
return:
['(())', '()()']
None

I think I modify ans list object on the line l.1 and return it, and on line l.2, I pass the ans reference on line l.3. But when I print both value ans and ret, ret does not contain same value as ans.

Of course, I just print ans out for correct answer but I expected Python initialized variable ret and assigned brackets return reference to ret on line l.3.

I got confused how python pass the reference through a function. Please let me know the relevant documents or the answer.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
JSKIM
  • 195
  • 13

2 Answers2

1

If the length of cur is not n*2, the brackets() function does not return any value. It isn't easy to know what it should return, to be honest, because you have not posted some expected results. That said, here are some options:

  1. Always return the value of the recursive call:

     if open < n:
         return brackets(ans, n,cur+"(",open+1,close)
    
     if open > close:
         return brackets(ans, n,cur+")",open,close+1)
    

    In this case, this will be the end result:

     ['(())']
     ['(())']
    

    or

  2. Return ans at the end of the function:

     return ans
    

    This will be the output:

     ['(())', '()()']
     ['(())', '()()']
    
brandizzi
  • 26,083
  • 8
  • 103
  • 158
0

This is because of variable scope. The variable inside the function brackets is different than the one outside the function, even if they have the same name (ans). Here is an article that might help you with this.

Ayush Garg
  • 2,234
  • 2
  • 12
  • 28