gpt4 book ai didi

python - 我的函数 closest_power(base, num) 在某些测试用例中失败

转载 作者:行者123 更新时间:2023-11-28 21:45:08 25 4
gpt4 key购买 nike

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

为什么我遗漏了这些案例?

最佳答案

您的第一个条件始终为真,直到违反条件。例如,如果 exp=1 => 4**1 <= 64 < 4**(1+1)屈服于真实。如果exp=2 => 4**2 <= 64 < 4**(2+1)也屈服于 true。

当违反条件时,结果总是等于较小的指数 (result=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

关于python - 我的函数 closest_power(base, num) 在某些测试用例中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com