gpt4 book ai didi

python - 递增 while 循环在某些测试用例中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:47 29 4
gpt4 key购买 nike

我必须定义一个函数,其中:

Starting with a positive integer original, keep multiplying original by n and calculate the sum of all multiples generated including original until the sum is no longer smaller than total. Return the minimum number of multiplications needed to reach at value at or above the given total.

例如:

  1. multiply_until_total_reached (1,5,2)

    1*2=2, (1+2)<5, 2*2=4, (1+2+4)>5, 需要2次乘法

  2. multiply_until_total_reached (1,15,2)

    1*2=2, (1+2)<15, 2*2=4, (1+2+4)<15, 4*2=8, (1+2+4+8)=15 , 3次乘法

我当前的代码可以工作,但在某些情况下返回值会相差 1。在 1,1038,2 的情况下,我需要 9 次乘法而不是 10 次,但在 1,15,2 的情况下,我得到正确的 (3) 次乘法。

这是我的代码:

def multiply_until_total_reached(original, total, n):
if total < original:
return 0
elif total > original:
sumofdigits = 0 #declares var to keep track of sum of digits to compare to total
timesofmult = 0 #track how many multiplication operations
while sumofdigits <= total + 1:
multnum = original * n
sumofdigits = multnum + original
original = multnum
sumofdigits = sumofdigits + multnum
timesofmult = timesofmult + 1
return timesofmult

是什么导致它关闭?

最佳答案

试试这个,更小更整洁。解释在评论中..

def multiply_until_total_reached(original, total, n):
sum = original #Initialize sum to original
mult_no = 0

while sum < total: #Will auto return 0 if original>=total
sum += original*n #Add original * n
original = original*n #Update the new original
mult_no += 1 #Increase multiplications by 1

return mult_no

print multiply_until_total_reached(1,5,2)
print multiply_until_total_reached(1,15,2)
print multiply_until_total_reached(1,1038,2)

#Output
#2
#3
#10

关于python - 递增 while 循环在某些测试用例中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42619190/

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