……續上回? Fibonacci數列高效解法大全及時間復雜度分析 連載【1】
4.? 生成器式尾遞歸解法
前面尾遞歸是用的return,在Python里還可以替換為yield,這樣尾遞歸函數就變成了尾遞歸生成器
變成yield尾遞歸有個好處,可以不用考慮棧空間限制了,不斷地next()直到獲得最終結果沒問題
def Fibonacci_sequence_04 (n: int) -> int:? #參數n是表示求第n項Fibonacci數
??? assert isinstance(n, int), 'n is an error of non-integer type.'
? ? import types
? ? def Calculate_Fibonacci_sequence (n: int, prev_num: int =0, current_num: int =1) -> int:
? ? ? ? '返回單項的yield式尾遞歸解法'
? ? ? ? if n>=2:
? ? ? ? ? ? yield Calculate_Fibonacci_sequence(n-1, current_num, prev_num+current_num)
? ? ? ? elif n==1:
? ? ? ? ? ? yield current_num
? ? if n>=1:
? ? ? ? var_cfs = Calculate_Fibonacci_sequence (n)
? ? ? ? while isinstance(var_cfs, types.GeneratorType):
? ? ? ? ? ? var_cfs = next(var_cfs)
? ? ? ? return var_cfs
? ? elif n==0:
? ? ? ? return 0
? ? else:
? ? ? ? return None
測時同前例,Total time: 0.006211秒
5.? yield from生成器式尾遞歸解法
yield作尾遞歸的生成器有個問題,就是不能直接用于for循環
解決辦法就是yield改成yield from。這樣就可以用for循環來獲取生成器的終值了。例如:
for?result in Fibonacci_sequence(n):
??? print(result)
但是,yield尾遞歸的無棧限制的好處就沒有了,當遞歸很深時,又重新出現了棧溢出
這是因為yield from對尾遞歸調用做了遞歸式yield生成器管道,就又冒出棧深度限制
破解之道就是還搬出“蹦床”技巧
尾遞歸生成器使用時為獲取終值還要套一層for,既然因為破解棧深限制加個裝飾器,那我正好把獲取終值功能也加進去。這樣使用尾遞歸生成器就跟函數一樣了,如:
Fibonacci_sequence(n)
下面來看完整的展開尾遞歸裝飾器及yield from尾遞歸解法斐波那契數
import functools
import inspect
import types
class TailCallException(Exception):
? ? def __init__(self, *args, **kwargs):
? ? ? ? self.args = args
? ? ? ? self.kwargs = kwargs
def Tail_recursion_generator_expansion(generator):
? ? '用于尾遞歸生成器展開的裝飾器代碼。使用方法:在定義生成器的前一行寫裝飾器“@Tail_recursion_generator_expansion”'
? ? @functools.wraps(generator)
? ? def wrapper(*args, **kwargs):
? ? ? ? frame = inspect.currentframe()
? ? ? ? if frame.f_back and frame.f_back.f_back and frame.f_code == frame.f_back.f_back.f_code:? #先判斷當前是否為遞歸調用(遞歸的話是_wrapper->被裝飾函數->_wrapper),再判斷是否存在前級和前前級調用
? ? ? ? ? ? raise TailCallException(*args, **kwargs)
? ? ? ? else:
? ? ? ? ? ? while True:
? ? ? ? ? ? ? ? try:
? ? ? ? ? ? ? ? ? ? g = generator(*args, **kwargs)
? ? ? ? ? ? ? ? ? ? while isinstance(g, types.GeneratorType):
? ? ? ? ? ? ? ? ? ? ? ? g=next(g)
? ? ? ? ? ? ? ? ? ? return g
? ? ? ? ? ? ? ? except TailCallException as e:
? ? ? ? ? ? ? ? ? ? args = e.args
? ? ? ? ? ? ? ? ? ? kwargs = e.kwargs
? ? return wrapper
def Fibonacci_sequence_05 (n: int) -> int: #參數n是表示求第n項Fibonacci數
??? assert isinstance(n, int), 'n is an error of non-integer type.'
? ? @Tail_recursion_generator_expansion
? ? def Calculate_Fibonacci_sequence (n: int, prev_num: int =0, current_num: int =1) -> int:
? ? ? ? '返回單項的yield from式尾遞歸解法'
? ? ? ? if n>=2:
? ? ? ? ? ? yield from Calculate_Fibonacci_sequence(n-1, current_num, prev_num+current_num)
? ? ? ? elif n==1:
? ? ? ? ? ? yield current_num
? ? if n>=1:
? ? ? ? return Calculate_Fibonacci_sequence (n)
? ? elif n==0:
? ? ? ? return 0
? ? else:
? ? ? ? return None
測時同前例,Total time: 0.013653秒
未完待續……