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

时间:2016-10-03 20:04:12

标签: 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

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

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

8

返回onCreateView(View view, ...)

为什么我错过了这些案件?

4 个答案:

答案 0 :(得分:5)

在违反条件的情况下,您的第一个条件始终为真。例如,如果exp=1 =&gt; 4**1 <= 64 < 4**(1+1)收益为真。如果exp=2 =&gt; 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 

答案 1 :(得分:0)

我认为elif是额外的。如果满足条件,则应返回值。

def closest_power2(base, num):
    exp=1
    while base**exp<=num:
        if base**exp <= num <= base**(exp+1):
           num_low = base**exp
           num_high = base**(exp+1)
           return exp if num-num_low<num_high-num else exp+1
        exp += 1
    return 0

嗯......在您的情况下,对于exp=8,第一个if条件得到满足。然后,您指定result=exp(即8)并在下一次迭代while中断,因为2^9不小于384,因此您返回8

请注意,我已将base**exp<num更改为base**exp<=num

答案 2 :(得分:0)

这有效。

Select a.*, p.AnaCount
from TIPOS_ANALISIS a join
    (select p.ID_ANA, count(*) as AnaCount
     from PETICIONES p
     group by p.ID_ANA
     order by AnaCount DESC
     limit 1
    ) p
    on a.ID_ANA = p.ID_ANA

答案 3 :(得分:0)

在最新的分级机中,以前的答案无效。您会想到一些使用敏感度术语的内容(例如epsilon)。因此,在这种情况下,找到适当指数的标准可能是实际估算值与下一个估算值的绝对差之内的不等式。

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.
    '''
    # Your code here
    n = num 
    while abs((base**n)-num)>=abs((base**(n-1))-num):
        n -= 1
    return int(n)