Python 斐波那契数列 Iterator 版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Fabonacci(object):
 
    def __init__(self, num):
        #fabonni number
        self.num = num
        self.a = 1
        self.b = 1
        self.current_index = 0
 
    # __iter__
    def __iter__(self):
        return self
 
    #__next__
    def __next__(self):
        #1. judge if exceed
        if self.current_index < self.num:
            data = self.a
            self.a, self.b = self.b, self.a + self.b
            self.current_index += 1
            print("index = %d, a = %d, b = %d" % (self.current_index, self.a, self.b))
            return data
        #2. exceed
        else:
            raise StopIteration
 
 
if __name__ == '__main__':
    fabo_iteration = Fabonacci(5)
    for value in fabo_iteration:
    # value = next(fabo_iteration)
        print(value)

 

posted @   筱筱的春天  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2018-03-21 http://xx.xxx.xxx.xx:8080/把路径设置成http服务访问的形式
2018-03-21 Scrapy: 初识Scrapy
点击右上角即可分享
微信分享提示