Skip to main content
 首页 » 编程设计

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

2025年05月04日24haluo1

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

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