算例:生成Fibonacci數列優化
【方法一】秒出結果!spa
1 a, b = 0, 1 2 for num in range(1, 101) 3 a, b = b, a + b 4 print(f'{num}: {a}')
【方法二】時間消耗特別長!code
def fib(num): if num in (1, 2): return 1 return fib(num - 1) + fib(num - 2) for num in range(1, 101): print(f'{num}: {fib(num)}')
【方法二改進】時間與空間不可兼得,要想優化時間,那就增長額外的存儲空間!blog
1 def fib(num, temp = {}) 2 if num in (1, 2): 3 return 1 4 if num not in temp: 5 temp[num] = fib(num - 1) + fib(num - 2) 6 return temp[num] 7 8 for num in range(1, 101) 9 print(f'{num}: {fib(num)}')