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=‘ ‘)

相关推荐