asfasf6525 asfasf6525 - 1 month ago 6
Python Question

My function closest_power(base, num) failing some test cases

def closest_power(base, num):
'''
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return the smaller value.
Returns the exponent.

'''

result=0
exp=1
while base**exp<num:
if base**exp <= num < base**(exp+1):
result = exp

elif num - base**exp <= base**(exp+1) - num:
result=exp+1

exp+=1
return result


In my code, when I try running
closest_power(4,62)
it returns
2
instead of
3
and, in similar test cases like
closest_power(4, 12)
returns
1
instead of
2
. (
closest_power(5, 22)
returns
1
instead of
2
)

For rest of the test cases it works fine for example:

closest_power(2, 384.0)


returns
8
.

Why am I missing out those cases?

Answer

Your first condition is always true until while condition violated. For example if exp=1 => 4**1 <= 64 < 4**(1+1) yields to true. If exp=2 => 4**2 <= 64 < 4**(2+1) also yields to true.

And when condition violated result is always equals to smaller exponent (result=exp). So calling closest_power(4,62) is same as calling closest_power(4,18) and returns 2.

As @wim said your method is too complicated. Something like below would be more clear:

def closest_power(base, num):
    '''
    base: base of the exponential, integer > 1
    num: number you want to be closest to, integer > 0
    Find the integer exponent such that base**exponent is closest to num.
    Note that the base**exponent may be either greater or smaller than num.
    In case of a tie, return the smaller value.
    Returns the exponent.

    '''
    exp=1
    while base ** exp < num:
        exp+=1
    return exp if base ** exp - num < num - base ** (exp - 1) else exp - 1 
Comments