0

this is my python program which is exercise 6.4 answer i put also.

#!/usr/bin/env python3

"""
Exercise 6.4.
A number, a, is a power of b if it is divisible by b and a/b is a power of b.
Write a function called is_power that takes parameters a and b and returns
True if a is a power of b.
Note: you will have to think about the base case.
"""

def is_power(a, b):
    """Checks if a is power of b."""
    if a == b:
        return True
    elif a%b == 0:
        return is_power(a/b, b)
    else:
        return False

print("is_power(10, 2) returns: ", is_power(10, 2))
print("is_power(27, 3) returns: ", is_power(27, 3))
print("is_power(1, 1)  returns: ",  is_power(1, 1))
print("is_power(10, 1) returns: ", is_power(10, 1))
print("is_power(3, 3)  returns: ",  is_power(3, 3))

I am getting this error, whenever i tried it again and again showing this error. Please guide me where is the mistake in my program.

is_power(10, 2) returns:  False
is_power(27, 3) returns:  True
is_power(1, 1)  returns:  True
Traceback (most recent call last):
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 23, in <module>
    print("is_power(10, 1) returns: ", is_power(10, 1))
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 16, in is_power
    return is_power(a/b, b)
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 16, in is_power
    return is_power(a/b, b)
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 16, in is_power
    return is_power(a/b, b)
  [Previous line repeated 1021 more times]
  File "C:\Users\Aaban Shakeel\Desktop\Think-Python-2e---my-solutions-master\ex6\ex6.4.py", line 13, in is_power
    if a == b:
RecursionError: maximum recursion depth exceeded in comparison

3 Answers3

0

This is because for b=1 your recursion will never end - I would add:

def is_power(a, b):
    """Checks if a is power of b."""
    if a == b:
        return True
    elif b==1:
        return False
    elif a%b == 0:
        return is_power(a/b, b)
    else:
        return False
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
0

You have to add extra check for number 1, because your algorithm gets stuck (param 'a' stops changing) in this line

is_power(a / b, b)

if b == 1 you call the same function forever (actually until you reach maximum recursion depth :P )

is_power(10 / 1, 1)
is_power(10 / 1, 1)
...

Recursion limit guards you from overflowing the stack.

RafalS
  • 5,834
  • 1
  • 20
  • 25
0

It seems like it is better to re-write the algorithm iteratively rather than using recursion. This is due to tail recursion is not efficient in python. More info: https://stackoverflow.com/a/3323013/5746085

hasi90
  • 84
  • 8