Answer to Question #100243 in Python for oladepo

Question #100243
Do Exercise 6.4 from your textbook using recursion and the is_divisible function from Section 6.4. Your program may assume that both arguments to is_power are positive integers. Note that the only positive integer that is a power of "1" is "1" itself.

After writing your is_power function, include the following test cases in your script to exercise the function and print the results:

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)
1
Expert's answer
2019-12-12T07:30:33-0500
def is_power(a,b):
   '''
   A number, a, is a power of b if it is divisible by b and a/b is a power of b.
   '''
   assert type(a) == int and type(b) == int and a > 0 and b > 0,\
       "is_power(a,b): both arguments must be positive integers"
   # 1st base case:
   # A number, a, is a power of b if both of them (a and b) are equal
   # N.B. The only positive integer that is a power of "1" is "1" itself,
   if a == b:
       result = True
   # 2nd base case:
   # There is no any positive integer that is a power of "1", except the "1"
   # itself, i.e., when b equals 1
   elif b == 1:
       result = False
   else:
       result = is_divisible(a,b) and is_power(a//b, b)
   assert type(result) == bool,\
       "is_power(a,b): the return result must be type of boolean"
   return result

def is_divisible(x, y):
   return x % y == 0

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))
print("is_power(121, 11) returns: ", is_power(121, 11))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS