Reputation: 405
I have a problem in my program. Code as follows:
def getHeight(self,root):
#Write your code here
if not root:
return -1
if root.left:
i = self.getHeight(root.left) + 1
if root.right:
j = self.getHeight(root.right) + 1
return max(i, j)
Raises the error:
Traceback (most recent call last):
File "solution.py", line 37, in
height=myTree.getHeight(root)
File "solution.py", line 23, in getHeight
i = self.getHeight(root.left) + 1
File "solution.py", line 23, in getHeight
i = self.getHeight(root.left) + 1
File "solution.py", line 27, in getHeight
return max(i, j)
UnboundLocalError: local variable 'i' referenced before assignment
And if I add i, j = 0, 0
, it will work well.
And following code:
if True:
i = 1 + 1
The code work well without initialization. Could someone please explain the difference?
Upvotes: 0
Views: 120
Reputation: 1221
When you write i, j = 0, 0
, you are initializing both variables to 0
.
When you write i = 1 + 1
, you are initializing i
to 2
, and because this is inside an if True
, that code is always executed. So, you don't need to write if True
as it will have the same effect.
To be clear, you always need to initialize variables before you read them. Always. What I am saying is that both corrections of your code are indeed initializing those variables. That's why they work.
Upvotes: 1
Reputation: 1
I think you should initial the variable before you reference it. In you code, the max function take the i, j as the argument.Thus the i, j need to be initialize. The if statement can't ensure the initialization, so the compiler gives you errors.
if true : i = 1 + 1
This code just assign the i with the value 2.
Upvotes: 0
Reputation: 191758
The condition is always.
The variable needs to be defined to be used. If the conditions are false, the variable is not defined.
You could use ternary statements instead to mitigate the issue
def getHeight(self,root):
if not root:
return -1
i = self.getHeight(root.left) + 1 if root.left else 0
j = self.getHeight(root.right) + 1 if root.right else 0
return max(i, j)
Upvotes: 0