Fabonacci算法
类思想实现
class Fabonacci:
def __init__(self):
self.b=[1,1] # 缓存计算结果
def __call__(self,p):
if p <= len(self.b): # 判断是否已经计算过
return self.b[p-1]
for v in range(len(self.b),p):
self.b.append(self.b[v-1]+self.b[v-2])
return self.b[p-1]
def __len__(self):
return len(self.b)
def __getitem__(self,item): # item默认为positive integer,
print(len(self),'&&&&&&&&&&&&&')
if item<0:
return None
if item-1>len(self)-1: # 长度不足,调用__call__(self,p)计算
self.__call__(item) # self(item)
print(len(self),'&'*30)
return self.b[item-1]
def __iter__(self):
return iter(self.b)
import time
start=time.time()
m=Fabonacci()
print(m(5))
end=time.time()
print(end-start)
print(m[7])
for pp in m:
print(pp)