• 迭代器协议item 和裴波拉切数列


     1 class Runf:
     2     
     3     def __init__(self,n):
     4         self.n=n
     5     # def __iter__(self):
     6     #     return  self
     7 
     8     def __next__(self):
     9         if self.n==12:
    10          raise StopIteration("程序异常终止了!")
    11         self.n+=1
    12         return self.n
    13 
    14 rf=Runf(10)
    15 
    16 # for i in rf:
    17 #     print(i)
    18 print(next(rf))
    19 print(next(rf))
    20 # print(next(rf)) #大于12抛异常
    21    

    裴波拉切数列:

     1 class Runf:
     2 
     3     def __init__(self):
     4         self._a=1
     5         self._b=1
     6     def __iter__(self):
     7         return  self
     8 
     9     def __next__(self):
    10         self._a,self._b=self._b,self._a+self._b
    11         return self._a
    12 
    13 rf=Runf()
    14 # print(rf.__next__())
    15 # print(rf.__next__())
    16 # print(rf.__next__())
    17 # print(rf.__next__())
    18 # print(rf.__next__())
    19 # print(rf.__next__())
    20 for i in rf:
    21     print(i)    #迭代器实现裴波拉切
    22 
    23 
    24 
    25 lis=[]
    26 for i in range(10):
    27     if i==0 or i==1:
    28         lis.append(1)
    29     else:
    30         lis.append(lis[i-2]+lis[i-1])
    31 print(lis)      #递归实现裴波拉切
    32 
    33 a=0
    34 b=1
    35 while b<60:
    36    print(b)
    37    a,b=b,a+b   #while循环实现
    裴波拉切
  • 相关阅读:
    「WC2021」表达式求值
    [补]「WC2021」括号路径
    「CEOI2020」星际迷航
    「CEOI2018」斐波那契表示法
    CF913F
    CF1017G The Tree
    NOI2020 超现实树
    LOJ 6714 Stupid Product
    LOJ 575. 不等关系
    CF1267G
  • 原文地址:https://www.cnblogs.com/wen-kang/p/9255156.html
Copyright © 2020-2023  润新知