0

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?

  • `myPow2` calls `self.myPow` again with a different value for `x`…!? – deceze Jul 19 '21 at 11:39
  • It is hard to understand recursion at first. I suggest you look up "tail recursion" on this site, for example, https://stackoverflow.com/questions/33923/what-is-tail-recursion/37010#37010 . – rajah9 Jul 19 '21 at 11:57

1 Answers1

2

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:
Fabio R.
  • 393
  • 3
  • 15