Python实现斐波那契数列

Posted zhirou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python实现斐波那契数列相关的知识,希望对你有一定的参考价值。

1、最普通的写法

def fibonaci(num):
    a = 0
    b = 1
    print(a, end=" ")
    for _ in range(num):
        c = a + b
        a = b
        b = c
        print(a, end=" ")

fibonaci(10)

2、Python风格的写法

def fibonaci(num):
    a = 0
    b = 1
    print(a, end=" ")
    for _ in range(num):
        a, b = b, a+b
        print(a, end=" ")

fibonaci(10)

3、Python的迭代器实现

class Fibonacci:
    def __init__(self, max_num):
        self.max_num = max_num
        self.current_num = 0
        self.first_num = 0
        self.second_num = 1

    def __iter__(self):
        return self

    def __next__(self):
        if self.current_num < self.max_num:
            result = self.first_num
            self.first_num, self.second_num = self.second_num, self.first_num + self.second_num
            self.current_num += 1
            return result
        else:
            raise StopIteration


# 创建斐波那契额对象
f = Fibonacci(10)
for i in f:
    print(i, end= )

 

以上是关于Python实现斐波那契数列的主要内容,如果未能解决你的问题,请参考以下文章

python实现斐波那契数列(Fibonacci sequence)

python实现斐波那契数列

Python手动编程实现斐波那契数列

Python实现斐波那契数列的方法以及优化

斐波那契数列(C++ 和 Python 实现)

编写一递归函数求斐波那契数列的前40项