一、迭代器实现
class myFibs(object):
def __init__(self, control):
self.a = 0
self.b = 1
self.control = control
self.item_index = 0
def __iter__(self):
return self
def __next__(self):
if self.item_index < self.control:
self.a, self.b = self.b, self.a + self.b
self.item_index += 1
return self.a
else:
raise StopIteration
if __name__ == "__main__":
result = int(input("请输入要产生'斐波拉契数列'的个数:"))
myfib = myFibs(result)
for index,item in enumerate(myfib):
print(f"{index+1} => {item}")
二、生成器实现
def Fibs(n):
a, b, counter = 0, 1, 0
while True:
if counter >= n:
return
a, b = b, a + b
yield a
counter = counter + 1
if __name__ == "__main__":
result = int(input("请输入要产生'斐波拉契数列'的个数:"))
myfib = Fibs(result)
for index, item in enumerate(myfib):
print(f"{index + 1} => {item}")
三、生成器+itertools实现
import itertools
def Fibs():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
if __name__ == "__main__":
result = int(input("请输入要产生'斐波拉契数列'的个数:"))
temp = itertools.islice(Fibs(), result)
for index, item in enumerate(temp):
print(f"{index + 1} => {item}")
希望本文对你有所帮助~~如果对接口测试、自动化测试、面试经验交流感兴趣可以加入我们。642830685,免费领取最新软件测试大厂面试资料和Python自动化、接口、框架搭建学习资料!技术大牛解惑答疑,同行一起交流。