Reputation: 157
I am writing a recursive solution to the following Leetcode problem: https://leetcode.com/explore/learn/card/recursion-i/256/complexity-analysis/2380/
It is simply to calculate x^n
, where x,n
are both integers
.
def myPow(self, x: float, n: int) -> float:
def myPow2(power_x,n):
if n ==1:
return power_x
print(x)
power_x = power_x*x
return self.myPow(power_x,n-1)
return myPow2(2,10)
My question is simple- for print x
above, I am getting 2,4,16,256,etc..
But why is x changing? If I take the line power_x = power_x*x
away, then x prints as 2,2,2,2,2...
as expected. I don't understand why that line would change x? Isn't x
always the input (2 in this case) - unless we reassign it, but here we don't reassign it?
Upvotes: 0
Views: 71
Reputation: 433
Look at your function definition:
def myPow(self, x: float, n: int) -> float:
and now at your function call:
return self.myPow(power_x,n-1)
you are probably passing power_x to x every time you call the function. My suggestion would be not to nest the definitions (if it's not required by the exercise) to increase readability and set myPow to
def myPow(self, power_x, x: float, n: int) -> float:
Upvotes: 2