-
递归生成斐波那契数列
def fib(n:int): if n <2: return n return fib(n-1) + fib(n-2)
-
给递归加个缓存
cache = {} def fib(n:int): if n<2: return n result = cache.get(n,None) if result is None: cache[n] = fib(n-1) + fib(n-2) return cache[n] return result
-
创建斐波那契数列迭代器
class Fib: def __init__(self,n:int): self.stop = n self.index = 1 self.a,self.b = 0,1 def __iter__(self): return self def __next__(self,): if self.index <= self.stop: self.a,self.b = self.b ,self.a+self.b self.index +=1 return self.a raise StopIteration
网友评论