斐波那契数列:后一个数为前两个数的和。由于要不断交换数字,要用的python的数字交换。
a = 2 b = 5 print(b) a, b = b, a + b print(b) a, b = b, a + b print(b)
用迭代器来做。
class
Test:
def
__init__
(self, a, b):
self.a = a
self.b = b
def__iter__(self):
return self
def__next__(self):
if self.b > 20:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return self.b
test = Test(0, 1)
for i in test: # for 循环就是在执行__next__print(i)
如果用生成器yield来做会简单很多。
def
shulie(a, b, max):
while b < max:
a, b = b, a + b
yield b # yield执行一次会退出并挂起。下次从挂起的地方继续for i in shulie(0, 1, 20): # for 循环就是在执行__next__print(i)
原文:https://www.cnblogs.com/liaoyifu/p/14137834.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!