Search code examples
pythonrecursionboolean

Function to tell if a is a power of b. Which is more accurate?


I have the following two implementations for determining whether a is a power of b. The second one is my own code, but the book I'm following gives the first code.

I asked AI bots, but they also prefer the first code.

Why is the first one considered more accurate than mine? Both give the same answers...

First code:

def is_power(a,b):
    if a % b != 0:
        return False
    if a == 1:
        return True
    else:
        return is_power(a//b,b)

Second code:

def is_power(a,b):
    if a % b != 0:
        return False
    if a//b == 1:
        return True
    else:
        return is_power(a//b,b)

Solution

  • You write:

    ... both gives the same answer

    They actually don't. For instance, for arguments a=2, b=2, the first returns False, the second True.

    But: neither works correctly.

    • Both return False for is_power(1, 2), yet 2⁰ = 1.
    • Both get into an infinite loop for is_power(2, 1) and for is_power(0, 1). They should return False.
    • Both produce a division-by-zero error when the second argument is 0, yet 0 is a power of 0 (using any strictly positive exponent)

    Using the same recursive pattern, using power//base, here is a corrected version for signed integer arguments:

    def is_power(power, base):
        def recur(power):
            if abs(power) < 2 or power % base:
                return power == 1
            return recur(power//base)
    
        if abs(base) < 2:
            return power in (1, base)
        return recur(power)