'''n = int(input("请输入一个整数:")) def fab(n): if n<1: print("输入有误!") return -1 if n == 1 or n == 2: return 1 else: return fab(n-1) + fab(n-2) result = [] for i in range(1,n+1): result.append(fab(i)) print(result) n = int(input("请输入一个整数:")) dic = {0:0,1:1} def fib(n): if n in dic: return dic[n] else: temp = fib(n-1) + fib(n-2) dic[n] = temp return temp for i in range(n): print(fib(i),end= " ")''' import sys def fibonacci(n): #生成器函数 - 斐波那契 a,b,counter = 0,1,0 while True: if counter > n: return yield a a,b = b, a + b counter += 1 f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print(next(f),end = " ") except StopIteration: sys.exit()
Python实现斐波那契额数列
最新推荐文章于 2023-12-31 13:11:56 发布