我的函数nearest_power(base,num)在某些测试用例中失败了

Vip*_*nha 2 python python-3.x

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
Run Code Online (Sandbox Code Playgroud)

在我的代码中,当我尝试运行时,closest_power(4,62)它返回2而不是3,在类似的测试用例中,如closest_power(4, 12)返回1而不是2.(closest_power(5, 22)返回1而不是2)

对于其余的测试用例,它可以正常工作,例如:

closest_power(2, 384.0) 
Run Code Online (Sandbox Code Playgroud)

回报8.

为什么我错过了那些案子?

alp*_*ert 5

在违反条件的情况下,您的第一个条件始终为真.例如,如果exp=1=> 4**1 <= 64 < 4**(1+1)yield为true.如果exp=2=> 4**2 <= 64 < 4**(2+1)也屈服为真.

当条件违反时,结果总是等于较小的指数(结果= exp).所以调用closest_power(4,62)与调用closest_power(4,18)和返回相同2.

正如@wim所说,你的方法太复杂了.下面的内容会更清楚:

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 
Run Code Online (Sandbox Code Playgroud)