Python 3.x 可视化递归的扩展和收缩过程
我正在练习SICP的练习1.17Python 3.x 可视化递归的扩展和收缩过程,python-3.x,sicp,Python 3.x,Sicp,我正在练习SICP的练习1.17 #+begin_src ipython :session alinbx :results output def fast_mul(a, b): if b == 1: return a else: if even(b): return 2 * fast_mul(a, b//2) if odd(b): return a + 2 * fast_mul(a, b//2) def even(n): return
#+begin_src ipython :session alinbx :results output
def fast_mul(a, b):
if b == 1: return a
else:
if even(b): return 2 * fast_mul(a, b//2)
if odd(b): return a + 2 * fast_mul(a, b//2)
def even(n):
return n % 2 == 0
def odd(n):
return n % 2 == 1
print(fast_mul(3, 7))
#+end_src
#+RESULTS:
: 21
如何通过添加print
as来查看扩展和收缩的过程
fast_mul(3,7)
3 + 2 * fast_mul(3, 3)
3 + 2 * (3 + 2 * fast_mul(3, 1))
3 + 2 * (3 + 2 * 3)
21
我在函数中又添加了两个参数,s和d
s存储从上一个递归调用带入的字符串
d存储递归的深度,这样我们就可以计算出要添加到字符串中的右括号的数量。听起来像是在寻找a,尽管默认值可能需要一些黑客操作才能返回您正在寻找的特定细节,例如
python -m trace -t fast_mul.py
在elisp中,默认跟踪更接近您想要的输出,例如
(defun fast-mul (a b)
(if (eq 1 b) a
(+ (if (evenp b) 0 a) (* 2 (fast-mul a (/ b 2))))))
(trace-function 'fast-mul)
(fast-mul 3 7)
;; 1 -> (fast-mul 3 7)
;; | 2 -> (fast-mul 3 3)
;; | | 3 -> (fast-mul 3 1)
;; | | 3 <- fast-mul: 3
;; | 2 <- fast-mul: 9
;; 1 <- fast-mul: 21
(解除快速mul(a b)
(如果(等式1b)a
(+(if(evenp b)0a)(*2(fast mul a(/b2щщ)))
(跟踪功能“快速mul”)
(快速mul 3 7)
;; 1->(快速mul 3 7)
;; | 2->(快速mul 3)
;; | | 3->(快速mul 3 1)
;; | | 如果你试着留下答案,我会非常感激@eshonaiii如果您继续这样做,也许可以像这样转储结果,尽管我不知道如何在不进入交互式调试程序的情况下立即执行,但我希望有一个通用的解决方案(一些包)来调试递归,它独立于指定的情况。
(defun fast-mul (a b)
(if (eq 1 b) a
(+ (if (evenp b) 0 a) (* 2 (fast-mul a (/ b 2))))))
(trace-function 'fast-mul)
(fast-mul 3 7)
;; 1 -> (fast-mul 3 7)
;; | 2 -> (fast-mul 3 3)
;; | | 3 -> (fast-mul 3 1)
;; | | 3 <- fast-mul: 3
;; | 2 <- fast-mul: 9
;; 1 <- fast-mul: 21