gpt4 book ai didi

Python 分析

转载 作者:太空狗 更新时间:2023-10-30 01:43:54 27 4
gpt4 key购买 nike

我用 Python 编写了几个用于生成阶乘的模块,我想测试运行时间。我找到了一个分析示例 here我使用该模板来分析我的模块:

import profile #fact

def main():
x = raw_input("Enter number: ")
profile.run('fact(int(x)); print')
profile.run('factMemoized(int(x)); print')

def fact(x):
if x == 0: return 1
elif x < 2: return x
else:
return x * fact(x-1)

def factMemoized(x):
if x == 0: return 1
elif x < 2: return x
dict1 = dict()
dict1[0] = 1
dict1[1] = 1
for i in range (0, x+1):
if dict1.has_key(i): pass
else: dict1[i] = i * dict1[i-1]
return dict1[x]

if __name__ == "__main__":
main()

但是,我收到以下错误:

Enter number: 10
Traceback (most recent call last):
File "fact.py", line 32, in <module>
main()
File "fact.py", line 7, in main
profile.run('fact(int(x)); x')
File "C:\Python27\lib\profile.py", line 70, in run
prof = prof.run(statement)
File "C:\Python27\lib\profile.py", line 447, in run
return self.runctx(cmd, dict, dict)
File "C:\Python27\lib\profile.py", line 453, in runctx
exec cmd in globals, locals
File "<string>", line 1, in <module>
NameError: name 'x' is not defined

知道我在这里做错了什么吗? TIA!~克雷格

最佳答案

正如 John Gaines Jr. 所说,profile.run() 存在一些作用域问题。但是,您可以将 runctx 与 globals() 和 locals() 一起使用,并显式提供上下文:

profile.runctx('fact(int(x)); print', globals(), locals())

显式比隐式好:)

关于Python 分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7637367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com