class FibIterator(object):
def __init__(self, n):
self.n = n
# 是使用current保存当前数列中第几个数
self.current = 0
# 使用num1保存数列中前一个数,初始值为0
self.num1 = 0
# 使用num2保存数列中后一个数,初始值为1
self.num2 = 1
def __next__(self):
# 判断迭代当前个数小于我们输入数字
if self.current < self.n:
num = self.num1
# 数列核心代码
self.num1, self.num2 = self.num2, self.num1+self.num2
self.current += 1
return num
else:
# 迭代完成抛出异常,停止迭代
raise StopIteration
def __iter__(self):
# 迭代器标志 ,返回自身
return self
# 程序入口
if __name__ == ‘__main__‘:
fib = FibIterator(5)
for num in fib:
print(num, end=" ")
输出结果:
0 1 1 2 3
def fib(n):
current = 0
num1, num2 = 0, 1
while current < n:
num = num1
num1, num2 = num2, num1+num2
current += 1
yield num
return
if __name__ == ‘__main__‘:
f = fib(5)
for _ in fib(5):
print(next(f), end=" ")
输出结果:
0 1 1 2 3
def fibonacci(n):
a, b = 0, 1
fib_list = [0,]
for _ in range(n - 1):
a, b = b, a + b
fib_list.append(a)
return fib_list
print(fibonacci(9))
输出结果:
[0, 1, 1, 2, 3, 5, 8, 13, 21]
原文地址:http://blog.51cto.com/10412806/2095505