Search code examples
pythondivide-and-conquer

Python Divide and Conquer Implementation of Nth Power of X


As a new python programmer, I'm working on a Leetcode question and don't know why my code does not work, so I really appreciate your advice:

Question:

Implement pow(x, n), which calculates x raised to the power n.

Example: Input: 2.00000, 10

Output: 1024.00000

Here is my python code (I tried to use divide and conquer concept):

class Solution:
    def myPow(self, x, n):
        if n == 0:
            return 0
        if n == 1:
            return x
        return self.power(x,n)
    def power(self,x,n):
        if n == 1:
            return x
        self.power(x,n//2)
        self.multiply(x,x)
        return x
    def multiply(self,x,y):
        x = x*y
        return x
test3=Solution()
test3.myPow(2,4)

But the results give 2 instead of 16. I expect the above code to work as follows:

power(2,4)->power(2,2)->power(2,1), which reaches the base case since n==1, and then we proceed with power(2,2),due to function multiply(x,x) or multiply(2,2) in this case, I expect x to become 4 (x = 2*2), and then we proceed with power(2,4), due to function multiply(x,x), x = 4*4 = 16

I don't know why I am wrong, could any expert give me some advice?


Solution

  • x^0 always equals 1, so your first "if" in myPow() is not accurate. Also, your power() function always returns x, because the lines:

    self.power(x,n//2)
    self.multiply(x,x)
    

    don't assign the value they return to anything.