Python计算斐波那契数列

分别用递归,动态编程和尾递归计算斐波那契数列

其中递归和动态编程的递归深度在我的电脑上大概能计算到斐波那契数列2500项左右,而尾递归则参考网上进行了递归优化对递归深度没有限制,以下是相应代码:

# -*- coding: utf-8 -*-
"""
Created on Sun May  5 08:53:27 2019

@author: Zha_Jiajia
"""

"""
Obtain Fibonacci series by recursion.
"""
def fib(n):
    if n <= 1:
        return n
    else:
        return fib(n-1) + fib(n-2)

"""
Obtain Fibonacci series by tail recursion.
reference: http://code.activestate.com/recipes/474088/
"""
import sys

class TailRecurseException(BaseException):
  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 as e:
          args = e.args
          kwargs = e.kwargs
  func.__doc__ = g.__doc__
  return func

@tail_call_optimized
def tail_fib(i, current_v = 0, next_v = 1):
  if i == 0:
    return current_v
  else:
    return tail_fib(i - 1, next_v, current_v + next_v)

"""
Obtain Fibonacci series by dynamic programming.
"""
def fastfib(n, mem):
    if n not in mem:
        mem[n] = fastfib(n-1, mem) + fastfib(n-2, mem)
    return mem[n]

def fib1(n):
    mem = {0:0, 1:1}
    return(fastfib(n, mem))
    

print(fib(35))
print(fib1(35))
print(tail_fib(35))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值