Python-斐波那契數列
阿新 • • 發佈:2018-12-16
# 迴圈
a = 0
b = 1
print('斐波那契數列: ', end='')
while b <= 1000:
print(b, end=' ')
a, b = b, a+b
# yield
def Fibo_Yield_tool(n): a, b = 0, 1 while n > 0: yield b a, b = b, a + b n -= 1 def Fibo_Yield(n): # return [f for i, f in enumerate(Fibo_Yield_tool(n))] # 列表解析,這種方式轉換速度很慢 return list(Fibo_Yield_tool(n)) # 直接轉化為list,這種方式比較快 if __name__ == '__main__': a = Fibo_Yield(10) # n代表位數 print(a)
# 遞迴
def Fibo_tool(n): if n <= 0: return 0 elif n == 1: return 1 else: return Fibo_tool(n - 1) + Fibo_tool(n - 2) def Fibo_Recursion(n): result_list = [] for i in range(1, n + 1): result_list.append(Fibo_tool(i)) return result_list if __name__ == '__main__': a = Fibo_Recursion(10) # 代表數列的位數 print(a)