Python - While循环简单

时间:2017-08-31 07:08:15

标签: python loops while-loop

我正在尝试编写一个函数,计算一种细菌为其初始种群达到最终种群所需的天数,因为每天它的种群数量增加一倍。我的代码是;

def num_doublings(initial_population, final_population):
   time = 0
   while initial_population < final_population:
       time+= 1
       initial_population = initial_population * 2
       print(time)

这会打印每一天,但我希望它只打印while循环停止所需的迭代总次数。使用num_doublings(2, 8)调用函数时,我的代码输出是

1
2
3

但我只需输出3.如何解决此问题?

5 个答案:

答案 0 :(得分:2)

你可以试试这个:

def num_doublings(initial_population, final_population):
    time = 0
    while initial_population <= final_population:
        time+= 1
        initial_population = initial_population * 2

    return time

该函数将返回时间变量,在您给出的示例中为3

答案 1 :(得分:2)

正如Martijn Pieters正确观察到的那样,高性能解决方案根本不使用循环:

from math import log, ceil

def num_doublings(initial, final):
    return ceil(log(final/initial, 2))

答案 2 :(得分:0)

您只需要在while循环外拉print行。像这样 -

def num_doublings(initial_population, final_population):
   time = 1
   while initial_population < final_population:
       time+= 1
       initial_population = initial_population * 2
   print(time)

请注意,我初始化time =1

答案 3 :(得分:0)

是范围问题,只需在modifyStock(id: number, quantity: number) { if (id == null || quantity == null) { return Observable.throw('Error'); } const url = `/item/${id}/modifyStock`; const body = { quantity: quantity }; return this.http.put(url, body); } 循环结束时打印数据:

while

答案 4 :(得分:-1)

取消缩进最后一行。

def num_doublings(initial_population, final_population):
   time = 0
   while initial_population < final_population:
       time+= 1
       initial_population = initial_population * 2
   print(time)