#coding=utf8
'''
利用四种方法实现斐波那契数列
'''
#第一种方法,是最最普通的一种方法
def fab1(max):
n, a, b = 0, 0, 1
while n < max:
print b
a, b = b, a + b
n = n + 1
print fab1(5)
#第二种方法,打印list
def fab2(max):
n, a, b = 0, 0, 1
L = []
while n < max:
L.append(b)
a, b = b, a + b
n = n + 1
return L
y = lambda x:fab2(x)
print y
#第三种方法,利用迭代器
class fab3(object):
def __init__(self, max):
self.max = max
self.n, self.a, self.b = 0, 0, 1
def __iter__(self):
return self
def next(self):
if self.n < self.max:
r = self.b
self.a, self.b = self.b, self.a + self.b
self.n = self.n + 1
return r
raise StopIteration()
print 'Three method'
for i in fab3(5):
print i
#Four method
def fab4(max):
n, a, b = 0, 0, 1
while n < max:
yield b
# print b
a, b = b, a + b
n = n + 1
print 'Four method'
for i in fab4(5):
print i
斐波那契数列的四种简单实现方式
最新推荐文章于 2021-10-22 21:20:43 发布