【问题标题】:Python function producing unexpected output [duplicate]Python函数产生意外的输出[重复]
【发布时间】:2021-11-07 05:18:42
【问题描述】:

我有以下 python 代码:

from time import time


def program1(a,b):
    for trial in range(5):
        start = time()
        a + b
        print (time() - start)
program1(27,59)

根据教程应该产生这个输出:

9.53674316406e-07
2.14576721191e-06
2.14576721191e-06
3.09944152832e-06
9.53674316406e-07

相反,它会产生:

0.0
0.0
0.0
0.0
0.0
>>> 

我试图用它来演示时间/空间复杂性的概念。

谁能解释一下输出以及为什么它不接受参数?

【问题讨论】:

  • a+b 发生得太快,无法在计算 time() - start 时获得任何分辨率。
  • 您能否建议我如何实现教程中所示的输出,以便向学生展示这一点,或者更好的方式来展示
  • 使用比a+b更复杂的东西。
  • time.sleep(1) 将创建 ~1 的输出
  • 如果你想展示时间复杂度,做一些时间依赖于trial

标签: python python-3.x loops variables output


【解决方案1】:

试试这个:

from time import time, sleep
import random


def program1(a,b):
    for trial in range(5):
        start = time() # gets current time

        time_to_sleep = random.random() # random() returns a number between 0 and 1
        
        # sleep will block the execution here for the number of seconds passed (0.5 is half a second for instance).
        sleep(time_to_sleep) 
        print (time() - start)
program1(27,59)

我添加了随机数以使其有点不可预测。

【讨论】:

  • Rafael - 会尝试 - 你能添加一些 cmets(用于教学目的)。解释正在发生的事情。例如, time() 到底在做什么(调用什么)。和 sleep.random
猜你喜欢
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 1970-01-01
相关资源
最近更新 更多