题目描述:
大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。
n<=39
解题方案:
首先就像用生成器的方法,但是这里没有太大的用。因为题目要求输出第n个数,而不是输出前n个数。不过还是采用了生成器的方法。
# -*- coding:utf-8 -*-
class Solution:
def fib_loop_while(self, max):
a, b = 0, 1
while max > 0:
a, b = b, a + b
max -= 1
yield a
def Fibonacci(self, n):
# write code here
result = self.fib_loop_while(n)
return next(result)
另外网上查找的一个有效方法,采用类实现内部魔法方法,定义迭代器。主要是实现iter()方法和next()方法。
class Fibonacci(object):
"""斐波那契数列迭代器"""
def __init__(self, n):
"""
:param n:int 指 生成数列的个数
"""
self.n = n
# 保存当前生成到的数据列的第几个数据,生成器中性质,记录位置,下一个位置的数据
self.current = 0
# 两个初始值
self.a = 0
self.b = 1
def __next__(self):
"""当使用next()函数调用时,就会获取下一个数"""
if self.current < self.n:
self.a, self.b = self.b, self.a + self.b
self.current += 1
return self.a
else:
raise StopIteration
def __iter__(self):
"""迭代器的__iter__ 返回自身即可"""
return self
if __name__ == '__main__':
fib = Fibonacci(15)
for num in fib:
print(num)