# Python尾递归优化

## 一般递归与尾递归

### 一般递归:

``````def normal_recursion(n):
if n == 1:
return 1
else:
return n + normal_recursion(n-1)``````

``````normal_recursion(5)
5 + normal_recursion(4)
5 + 4 + normal_recursion(3)
5 + 4 + 3 + normal_recursion(2)
5 + 4 + 3 + 2 + normal_recursion(1)
5 + 4 + 3 + 3
5 + 4 + 6
5 + 10
15``````

### 尾递归

``````def tail_recursion(n, total=0):
if n == 0:
else:
return tail_recursion(n-1, total+n)``````

``````tail_recursion(5, 0)
tail_recursion(4, 5)
tail_recursion(3, 9)
tail_recursion(2, 12)
tail_recursion(1, 14)
tail_recursion(0, 15)
15``````

## C中尾递归的优化

gcc使用`-O2`参数开启尾递归优化:

``````int tail_recursion(int n, int total) {
if (n == 0) {
}
else {
return tail_recursion(n-1, total+n);
}
}

int main(void) {
int total = 0, n = 4;
tail_recursion(n, total);
return 0;
}``````

``````\$ gcc -S tail_recursion.c -o normal_recursion.S
\$ gcc -S -O2 tail_recursion.c -o tail_recursion.S gcc开启尾递归优化``````

## Python开启尾递归优化

cpython本身不支持尾递归优化, 但是一个牛人想出的解决办法：`实现一个 tail_call_optimized 装饰器`

``````#!/usr/bin/env python2.4
# This program shows off a python decorator(
# which implements tail call optimization. It
# does this by throwing an exception if it is
# it's own grandparent, and catching such
# exceptions to recall the stack.

import sys

class TailRecurseException:
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs

def tail_call_optimized(g):
"""
This function decorates a function with tail call
optimization. It does this by throwing an exception
if it is it's own grandparent, and catching such
exceptions to fake the tail call optimization.

This function fails if the decorated
function recurses in a non-tail context.
"""
def func(*args, **kwargs):
f = sys._getframe()
if f.f_back and f.f_back.f_back \
and f.f_back.f_back.f_code == f.f_code:
# 抛出异常
raise TailRecurseException(args, kwargs)
else:
while 1:
try:
return g(*args, **kwargs)
except TailRecurseException, e:
args = e.args
kwargs = e.kwargs
func.__doc__ = g.__doc__
return func

@tail_call_optimized
def factorial(n, acc=1):
"calculate a factorial"
if n == 0:
return acc
return factorial(n-1, n*acc)

print factorial(10000) ``````

sys._getframe([depth]):
Return a frame object from the call stack.
If optional integer depth is given, return the frame object that many calls below the top of the stack.
If that is deeper than the call stack, ValueEfror is raised. The default for depth is zero,
returning the frame at the top of the call stack.

``````import sys

def get_cur_info():
print sys._getframe().f_code.co_filename  # 当前文件名
print sys._getframe().f_code.co_name  # 当前函数名
print sys._getframe().f_lineno # 当前行号
print sys._getframe().f_back # 调用者的帧``````

#### 你可能感兴趣的

1 条评论
ukeyim · 2017年04月26日

“开启尾递归优化前, 使用call调用函数, 创建了新的调用栈(LBB0_3);”
(LBB0_3)不是应该是做完所有的循环(call _tail_recursion之后压栈压栈）以后执行的嘛， 这里“新的调用栈”是什么意思啊？