国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python中尾遞歸用法實例詳解

2019-11-25 17:37:53
字體:
來源:轉載
供稿:網友

本文實例講述了python中尾遞歸用法。分享給大家供大家參考。具體分析如下:

如果一個函數中所有遞歸形式的調用都出現在函數的末尾,我們稱這個遞歸函數是尾遞歸的。當遞歸調用是整個函數體中最后執行的語句且它的返回值不屬于表達式的一部分時,這個遞歸調用就是尾遞歸。尾遞歸函數的特點是在回歸過程中不用做任何操作,這個特性很重要,因為大多數現代的編譯器會利用這種特點自動生成優化的代碼。

原理:

當編譯器檢測到一個函數調用是尾遞歸的時候,它就覆蓋當前的活躍記錄而不是在棧中去創建一個新的。編譯器可以做到這點,因為遞歸調用是當前活躍期內最后一條待執行的語句,于是當這個調用返回時棧幀中并沒有其他事情可做,因此也就沒有保存棧幀的必要了。通過覆蓋當前的棧幀而不是在其之上重新添加一個,這樣所使用的棧空間就大大縮減了,這使得實際的運行效率會變得更高。因此,只要有可能我們就需要將遞歸函數寫成尾遞歸的形式.

代碼:

# 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 sysclass TailRecurseException: def __init__(self, args, kwargs):  self.args = args  self.kwargs = kwargsdef 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_optimizeddef factorial(n, acc=1): "calculate a factorial" if n == 0:  return acc return factorial(n-1, n*acc)print factorial(10000)# prints a big, big number,# but doesn't hit the recursion limit.@tail_call_optimizeddef fib(i, current = 0, next = 1): if i == 0:  return current else:  return fib(i - 1, next, current + next)print fib(10000)# also prints a big number,# but doesn't hit the recursion limit.

希望本文所述對大家的Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 丁青县| 赤水市| 安丘市| 富平县| 永仁县| 杨浦区| 兴文县| 定西市| 金川县| 肃宁县| 九江县| 乌拉特后旗| 大埔区| 焉耆| 灯塔市| 武冈市| 河西区| 资阳市| 怀安县| 始兴县| 普格县| 鄂伦春自治旗| 十堰市| 股票| 仙游县| 镇安县| 临洮县| 什邡市| 潍坊市| 怀远县| 慈溪市| 平阴县| 新巴尔虎右旗| 闽清县| 丹东市| 漯河市| 北流市| 马公市| 辽阳市| 黔西| 丰原市|