美文网首页
斐波那契数列

斐波那契数列

作者: 青哥DevOps | 来源:发表于2020-01-04 15:12 被阅读0次

    f(3) =f(1)+f(2)
    f(n+2)=f(n)+f(n+1)
    f(1)=f(2)=1
    当n=100时,求f(n)?
    由题可知,这是一个斐波那契?

    # -*- coding:utf-8 -*-
    
    
    # 第一种
    def fab(max):
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b = b, a+b
            n += 1
    
    for i in fab(5):
        print i
    
    
    # 第二种
    def Fibonacci_Recursion_tool(n):
        if n <= 0:
            return 0
        elif n == 1:
            return 1
        else:
            return Fibonacci_Recursion_tool(n-1)+Fibonacci_Recursion_tool(n-2)
    
    
    def Fibonacci_Recursion_list(n):
        lis = []
        for i in xrange(1, n+1):lis.append(Fibonacci_Recursion_tool(i))
        return lis
    print Fibonacci_Recursion_list(5)
    
    #第三种
    resu_list = []
    def fibo(n):
        for i in xrange(n):
            if i == 0 or i == 1:
                resu_list.append(i)
            else:
                resu_list.append(resu_list[i-1]+resu_list[i-2])
        return resu_list
    
    print fibo(20)
    
    [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
    
    #第四种
    a = 0
    b = 1
    while b < 1000:
        print(b,end=',')
        a, b = b, a+b
    
    #第五种
    # -*- coding:utf-8 -*-
    
    class Fib(object):
        def __init__(self):
            pass
    
        def __call__(self, num):
            a, b = 0, 1;
            self.l = []
    
            for i in range(num):
                self.l.append(a)
                a, b = b, a + b
            return self.l
    
        def __str__(self):
            return str(self.l)
    
        __repr__ = __str__
    
    
    f = Fib()
    print f(3)
    
    [0, 1, 1]

    相关文章

      网友评论

          本文标题:斐波那契数列

          本文链接:https://www.haomeiwen.com/subject/zmaxactx.html