递归编程中的执行、复杂度与优化策略
1. 栈跟踪
栈跟踪是调试程序时非常有用的概念,它描述了程序执行过程中某一特定时刻的程序栈状态。大多数编程语言都提供了显示栈跟踪的功能,在 Python 中可以通过 traceback 模块来实现栈跟踪。
当程序出现运行时错误时,通常会打印栈跟踪信息。例如,将以下代码中的加法运算符替换为减法运算符:
s = s - u[i]*v[i]
这显然是错误的,因为其他依赖于 dot_product 的函数也会出错。当尝试计算一个(非零)向量的欧几里得范数时,会导致运行时错误,因为程序会尝试计算负数的平方根。运行代码时,标准 Python 解释器会打印类似如下的消息:
Traceback (most recent call last):
File "traceback_example.py", line 18, in <module>
print(cosine(a,b))
File "traceback_example.py", line 13, in cosine
return dot_product(u,v)/norm_Euclidean(u)/norm_Euclidean(v)
File "traceback_example.py", line 10, in norm_Euclidean
return math.sqrt(dot_product(v,v))
超级会员免费看
订阅专栏 解锁全文
173万+

被折叠的 条评论
为什么被折叠?



