You are forgetting a base case, when a == 1:
def isPower(a,b):
if a == 1:
return True
if a % b != 0:
return False
elif isPower((a/b),b):
return True
else
return False
However this has some other problems - if a is 0 then it will never finish and if b is 0 then you will get a divide-by-zero.
Here is a verbose solution that as far as I can tell will work for all integer combinations:
def isPower(a,b):
if a == 0 or b == 0:
return False
def realIsPower(a, b):
if a == 1:
return True
elif a%b != 0:
return False
elif realIsPower((a/b), b):
return True
else:
return False
return realIsPower(a, b)
EDIT: My code didn't work for cases when both a and b are negative. I'm now comparing their absolute values.
EDIT2: Silly me, x^0 == 1, so a == 1 should ALWAYS return true. That also means I don't have to compare a to b before the recursion. Thanks @Javier.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…