• 迭代器斐波那契数列


     1 class Num:
     2     total1 = 0
     3 
     4     def __init__(self, num, num1):
     5         self.num = num
     6         self.num1 = num1
     7 
     8     def __iter__(self):
     9         return self
    10 
    11     def __next__(self):
    12         if self.num>100:
    13             raise StopIteration('终止了')
    14         self.num,self.num1 = self.num1,self.num+self.num1
    15         return self.num
    16 n1 = Num(1,2)
    17 # for i in n1:
    18 #     print(i)
    19 print(n1.__next__())
    20 print(n1.__next__())
    21 print(n1.__next__())
    22 print(n1.__next__())
    23 print(n1.__next__())
    24 print(n1.__next__())
    25 print(n1.__next__())
    26 print(n1.__next__())
    27 print(n1.__next__())
    28 print(n1.__next__())
    29 print(n1.__next__())
    30 输出:
    31 2
    32 3
    33 5
    34 8
    35 13
    36 21
    37 34
    38 55
    39 89
    40 144
    41 Traceback (most recent call last):
    42   File "C:/Users/Administrator/Desktop/python/3月9日/斐波那契数列.py", line 29, in <module>
    43     print(n1.__next__())
    44   File "C:/Users/Administrator/Desktop/python/3月9日/斐波那契数列.py", line 13, in __next__
    45     raise StopIteration('终止了')
    46 StopIteration: 终止了

    斐波那契数列   可以用交换元素直接进行处理   a,b = b,a+b

  • 相关阅读:
    POJ 3071 概率DP
    BZOJ 2427 /HAOI 2010 软件安装 tarjan缩点+树形DP
    POJ 1155 树形DP
    POJ 3252 组合数学?
    POJ 3641 快速幂
    POJ 3180 Tarjan
    POJ 3185 DFS
    POJ 3260 DP
    POJ 2392 DP
    99. Recover Binary Search Tree
  • 原文地址:https://www.cnblogs.com/ch2020/p/12449380.html
Copyright © 2020-2023  润新知