Reputation: 79
So I wrote a code which is supposed to get the parent of a given node in a tree. Here is the pseudo code. Starting from the root,
def parent(self, child):
if right child exists:
if the right child == child:
return self
else: self.right.parent(child)
if left child exists:
if the left child == child:
print('f')
return self
else: self.left._get_parent(node)
I keep coming across this problem over and over and over again.
For the if the left child == child:
statement, the function DOES enter the if
statement if it finds that either the left child == child
or the right child == child
.
However, the return statement does not execute this. I know this because when I wrote the if the left child == child:
and wrote print('f')
after it, it did print f
, however, it did not return self
. Does anyone know why and can anyone give a solution as to how to fix this problem?
Additionally, does anyone know how to return two statements at once NOT as tuples or lists? For example, if I want to return 1 and 2,
def x(n):
return 1, 2
This would return (1, 2)
.. is there any way for it to not return it as a tuple? And just to return it normally. I'm asking this because when it comes to recursion, I want to call the same function on 1 AS WELL AS 2, and not on the tuple (1, 2)
.
Upvotes: 0
Views: 69
Reputation: 1121814
Your code discards the return values of recursive calls in the else:
branches. You need more return
statements:
if right child exists:
if the right child == child:
return self
else:
return self.right.parent(child)
if left child exists:
if the left child == child:
print('f')
return self
else:
return self.left._get_parent(node)
In Python, the expression 1, 2
creates a tuple, and that is the canonical way to return multiple values from functions. That is how multiple value returns work, by returning a tuple.
Simply unpack the returned value:
def foo():
return 1, 2
value1, value2 = foo()
or use indexing:
values = foo()
values[0], values[1]
Upvotes: 2