求助
import timedef x(a):
start = time.time()
while a != 1:
return a * x(a-1)
else :
return 1
stop = time.time()
print(stop - start)
为什么这里调用x()不显示时间
import time
def x(a):
while a != 1:
return a * x(a-1)
else :
return 1
def y(a):
start = time.time()
print(x(a))
stop = time.time()
return(stop - start)
而要单独定义一个新函数才能显示调用时间 本帖最后由 jackz007 于 2022-10-24 23:31 编辑
import time
def x(a):
start = time.time()
if a != 1: # 这里用 if 更加合理
return a * x(a-1)
else :
return 1
stop = time.time() # if 的 两个分支都有 return,这两句永远都没有机会被执行
print(stop - start)
start = time.time()
print(x(100))
stop = time.time()
print(stop - start) 因为函数遇到return就结束了,不会再执行return之后的语句 import time
def x(a):
start = time.time()
while a != 1:
return a * x(a-1)
else :
return 1
stop = time.time()
print(stop - start)
while...else 两个分支执行时必须进去一个
所以会直接return
若你想统计时间的话,应该这样写
import time
def x(a):
start = time.time()
while a != 1:
return a * x(a-1)
else :
return 1
print(stop - start)
n=int(input())
x(n)
stop = time.time()
print(stop - start)
页:
[1]