简体   繁体   中英

How to calculate power of?

def is_power_of(number, base):
  # Base case: when number is smaller than base.
  if number < base:
    # If number is equal to 1, it's a power (base**0).
    return True

  # Recursive case: keep dividing number by base.
  return is_power_of(number/base , base)

print(is_power_of(8,2)) # Should be True
print(is_power_of(64,4)) # Should be True
print(is_power_of(70,10)) # Should be False

The only thing I changed was the True and number/base, base . I can't figure out how to make True be true for all cases except for.=1.

Since it comes down to whether number == 1 or not, you can return that bool directly:

def is_power_of(number, base):
  # Base case: when number is smaller than base.
  if number < base:
    # If number is equal to 1, it's a power (base**0).
    return number == 1

  # Recursive case: keep dividing number by base.
  return is_power_of(number/base , base)

The outputs for your tests are:

True
True
False

which are expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM