使用迭代器实现斐波那契数列
>>> class fibs:
... def __init__(self,n=100):
... self.a = 0
... self.b = 1
... self.n = n
... def __iter__(self):
... return self
... def __next__(self):
... self.a,self.b=self.b,self.a+self.b
... if self.a>self.n:
... raise StopIteration
... return self.a
...
>>> fi = fibs()
>>> for i in fi:
... print(i,end=' ')
...
1 1 2 3 5 8 13 21 34 55 89 >>>
>>> fi = fibs(200)
>>> for i in fi:
... print(i,end=' ')
...
1 1 2 3 5 8 13 21 34 55 89 144 >>>
>>>
使用for循环实现斐波那契数列
利用列表的切片方法,根据斐波那契数列的规律,从第三项开始,后一个数值是前两个数值之和
>>> fibs = [1,1]
>>> for i in range(10):
... fibs.append(fibs[-1] + fibs[-2])
...
>>> print(fibs)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
>>>
使用while循环实现斐波那契数列
利用while循环功能
>>> a = 1
>>> b = 1
>>> while a<100:
... print(a,end = ' ')
... a,b = b,a+b
...
1 1 2 3 5 8 13 21 34 55 89
>>>
利用生成器实现斐波那契数列
# 利用生成器实现斐波那契数列
>>> def fibs(max):
... a = 0
... b = 1
... n = 0
... while n<max:
... a,b = b,a+b
... yield a
... n +=1
...
>>> fi = fibs(10)
>>> fi
<generator object fibs at 0x101ce5ba0>
>>> next(fi)
1
>>> next(fi)
1
>>> next(fi)
2
>>> for i in fi:
... print(i)
...
3
5
8
13
21
34
55
>>>