无法使用3个参数测试函数slowest_call
。
这是我的学习练习之一。首先,我定义了time_call
函数,然后尝试将其用作另一个函数slowest_call
的输入。
也许我的输入不太正确(我可以把什么作为第四输入?!)。不知道还有什么尝试。
from time import sleep
from time import time
t = time()
sleep(duration)
"""Return the amount of time the given function takes (in seconds) when called with the given argument """
def time_call(fn, arg):
t0 = time()
fn(arg)
t1 = time()
elapsed = t1 - t0
return elapsed
time_call(sleep, 4) # testing it, it works
""""Return the amount of time taken by the slowest of the following function
calls: fn(arg1), fn(arg2), fn(arg3) """
def slowest_call(fn, arg1, arg2, arg3):
return max(time_call(fn, arg1), time_call(fn, arg2), time_call(fn, arg3))
我正在这样测试
slowest_call(time_call(sleep,5), time_call(sleep,3), time_call(sleep,2))
TypeError: slowest_call() missing 1 required positional argument: 'arg3'
它给了我错误,它应该产生最长的时间作为答案(5 ...)。
答案 0 :(得分:1)
但这根本不是您的slowest_call
函数所期望的调用方式。它需要可调用函数本身,然后要使用三个参数来调用它。并且它会为您呼叫time_call
。所以:
slowest_call(sleep, 5, 3, 2)