# Fibonacci数列高效解法大全及时间复杂度分析　连载【3】

……续上回Fibonacci数列高效解法大全及时间复杂度分析　连载【2】

6.  非尾递归的实用化方案

from functools import wraps

def recursive_function_cache(func: function) -> function_value:

'用于缓存递归函数的装饰器代码。使用方法：在定义函数的前一行写装饰器“@recursive_function_cache”'

cache = dict()

@wraps(func)

def wrapper(*args, **kwargs):

parameters = (repr(args), repr(kwargs))

if parameters not in cache:

cache.update({parameters : func(*args, **kwargs)})

return dict.get(cache, parameters)  #返回缓存的函数值

return wrapper

>>> print('Fibonacci number= ', Fibonacci_sequence_02(100))

Fibonacci number= 354224848179261915075

>>> print('Fibonacci number= ', Fibonacci_sequence_02(1200))

RecursionError: maximum recursion depth exceeded while calling a Python object

import sys

def dynamic_increase_recursion_limit(func_str: string) -> eval:

'加载可能溢出的递归函数，动态增加栈空间限制值。使用方法：dynamic_increase_recursion_limit("函数(参数)")'

Increased_limit = 1000

previous_recursion_limit = sys.getrecursionlimit()

while True:

try:

result = eval(func_str)

sys.setrecursionlimit(previous_recursion_limit)

return result

except RecursionError:

sys.setrecursionlimit(sys.getrecursionlimit() + Increased_limit)

>>> print('Fibonacci number= ', dynamic_regulation_recursion_limit('Fibonacci_sequence_02(1200)'))

Fibonacci

number=

54877108839480000051413673948383714443800519309123592724494953427039811201064341234954387521525390615504949092187441218246679104731442473022013980160407007017175697317900483275246652938800

Fibonacci数列高效解法大全及时间复杂度分析　连载【4】