【Python】斐波那契数列
斐波那契数列(Fibonacci sequence),又称黄金分割数列[0、1、1、2、3、5、……]
F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)
class run_case: def feb(self, n: int): """ 斐波那契数列 :param n: 位数 :return: list """ try: if n > 0: feb_list = [] for i in range(n): if i <= 1: a = i else: a = feb_list[i-1] + feb_list[i-2] feb_list.append(a) print("{}位斐波那契数列列表:{}".format(num, feb_list)) print("第{}位为:{}".format(num, feb_list[num - 1])) return feb_list else: print("请输入正整数") # return 0 except Exception as e: print("异常原因:", e) if __name__ == "__main__": print("") # num = int(input("请输入想要的斐波那契数列的位数:")) num = 3 run_case().feb(num)
方法一:
# 斐波那契数列, 特点 [0, 1, 1, 2, 3, ……, fn = f n-1 + f n-2 ] def fab(self, n): try: # 判断n的有效性 if isinstance(n, int) == False or n <= 0: print("传递的参数必须为正整数") return False # 当n=1 时 斐波那契数列的第一位数=0 elif n == 1: return 0 else: # 前两位赋值 a, b = 0, 1 fab_list = [0, 1] for i in range(n - 2): a, b = b, a + b fab_list.append(b) print(fab_list) return fab_list except Exception as e: print("传递参数异常") return False
fab(12)
--------------------------------------------------------------
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 进程已结束,退出代码为 0
方法二:
def fibonacci(n): # 生成器函数 - 斐波那契 a, b, counter = 0, 1, 1 while True: if (counter > n): return yield a a, b = b, a + b counter += 1 if __name__ == "__main__": f = fibonacci(10) # f 是一个迭代器,由生成器返回生成 while True: try: print(next(f), end=" ") except StopIteration: sys.exit()
执行结果:
方法三:
def feib(n): if n <= 1: return n else: return (feib(n-1) + feib(n-2)) if __name__ == "__main__": inu = int(input("输入斐波那契数列位数:")) if inu < 0: print("输入正整数") else: for i in range(inu): print(feib(i))
执行结果:
-------------------------------------------------------------------------------------
如果万事开头难 那请结局一定圆满 @ Phoenixy
-------------------------------------------------------------------------------------