フィボナッチ.py
素朴な再帰版
code:python
def f(n):
global count
count += 1
if n == 0 or n == 1:
return 1
return f(n-1) + f(n-2)
max = int(input('第何項まで?'))
for i in range(max):
count = 0
print(i, f(i), count)
メモ化再帰版
code:python
import numpy as np
def f(n):
global memo, count
count += 1
max = int(input('第何項まで?'))
for i in range(max):
count = 0
memo = np.zeros((max,),dtype='uint64') # メモ用の0で初期化された配列
memo0 = memo1 = 1 # はじめの2項の値は1 print(i, f(i), count)