sách gpt4 ăn đã đi

Phân tích Python

In lại 作者:太空狗 更新时间:2023-10-30 01:43:54 27 4
mua khóa gpt4 giày nike

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

import profile #fact

định nghĩa 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
khác:
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__":
chủ yếu()

但是,我收到以下错误:

Enter number: 10
Theo dõi (cuộc gọi gần đây nhất là cuộc gọi cuối cùng):
File "fact.py", line 32, in
chủ yếu()
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 "", line 1, in
NameError: name 'x' is not defined

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

câu trả lời hay nhất

正如 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
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress