python实现斐波那契数列的几种方法,供参考

程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。

在数学上,费波那契数列是以递归的方法来定义:

F0 = 0     (n=0)
F1 = 1    (n=1)
Fn = F[n-1]+ F[n-2](n=>2)

收集了10种实现的方法:

方法1

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def fib(n):
    a,b = 1,1
    for i in range(n-1):
        a,b = b,a+b
    return a
 
# 输出了第10个斐波那契数列
print fib(10)

方法2

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 使用递归
def fib(n):
    if n==1 or n==2:
        return 1
    return fib(n-1)+fib(n-2)
 
# 输出了第10个斐波那契数列
print fib(10)

方法三

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def fib(n):
    if n == 1:
        return [1]
    if n == 2:
        return [1, 1]
    fibs = [1, 1]
    for i in range(2, n):
        fibs.append(fibs[-1] + fibs[-2])
    return fibs
 
# 输出前 10 个斐波那契数列
print fib(10)

方法4

#!/usr/bin/env python
#coding:utf-8

# 输出第n个数

n = int(raw_input("第几个数: "))

# 斐波那契数列的通项公式
f =(1/(5**0.5))*(((1+(5**0.5))/2)**n - ((1-(5**0.5))/2)**n)
print "%d个数:"%n,int(f)

# 输出前n个数列:
l=[1]
for i in range(1,n+1):
    f=(1/(5**0.5))*(((1+(5**0.5))/2)**i - ((1-(5**0.5))/2)**i)
    l.append(int(f))

方法5

#!/usr/bin/python
# -*- coding: UTF-8 -*-

def Fib(n):
    a, b = 0, 1
    while n:
        a, b, n = b, a + b, n - 1
        print(a)
Fib(7)

方法6

#!/usr/bin/env python
#coding:utf-8

#斐波拉契数列---使用生成器
def fib(max):
    n,a,b = 0,0,1
    while n < max:
        yield b
        a,b = b,a+b
        n += 1
max = int(input('input max num :'))
for n in fib(max):
    print(n)

方法7

#!/usr/bin/env python
#coding:utf-8

list = []
a = 1
list.append(a)    # 第一个
b = 1
list.append(b)    # 第二个
for i in range(1,20):  # 再输出接下来的 19 
    c = list[i-1]+list[i]
    list.append(c)
print list   # 输出 21 

方法8

#!/usr/bin/python3

from functools import lru_cache

@lru_cache(None)
def f(n):
    assert n >= 0
    return n if n <= 1 else f(n - 1) + f(n - 2)


print(f(10))

方法9 python3

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

class Fibs:
    def __init__(self, n = 10):
        self.a = 0
        self.b = 1
        self.n = n
        self.i = 0
    def __iter__(self):
        return self
    def __next__(self):
        self.a, self.b = self.b, self.a+self.b
        self.i += 1
        if self.i > self.n:
            raise StopIteration
        return self.a
fibs=Fibs(10)
for i in fibs:
    print (i)

方法10

#!/usr/bin/python
# -*- coding: UTF-8 -*-

l=[0,1]
for i in range(10):
    l.append(reduce (lambda x,y:x+y,l[-1:-3:-1]))
print l

方法10


# -*- coding: UTF-8 -*-

fe_list = [0, 1]
for i in range(1,11):
    fe_list.append(sum(fe_list[(i-1):(i+1)]))

print fe_list