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...
def is_power(a,b):
if a % b != 0:
return False
if a == 1:
return True
else:
return is_power(a//b,b)
def is_power(a,b):
if a % b != 0:
return False
if a//b == 1:
return True
else:
return is_power(a//b,b)
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.
is_power(1, 2)
, yet 2⁰ = 1.is_power(2, 1)
and for is_power(0, 1)
. They should return False.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)