带有缓存的迭代器
# 帕斯卡三角形
mCache = {}
def pascalWithDict(n,k):
if n==k or k==0 or n==1:
return 1
if k==1:
return n
if mCache.has_key((n,k)):
return mCache[(n,k)]
else:
mCache[n,k] = pascalWithDict(n-1,k-1)+pascalWithDict(n-1,k)
return mCache[n,k]
## 获得每行pascal列表
def generatePascal(depth):
lines = []
for row in range(depth):
line = []
for col in range(row+1):
line.append(pascal(row, col))
lines.append(line)
return lines
if __name__ == "__main__":
high = int(raw_input("pls enter the height of pascal:"))
lines = generatePascal(high)
for i in range(high):
print lines[i]
结果如下:
pls enter the height of pascal:6
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
使用装饰器的迭代器
from functools import wraps
def memo(func):
cache={}
@wraps(func)
def wrap(*args):
if args not in cache:
cache[args]=func(*args)
return cache[args]
return wrap
@memo
def pascal(n,k):
if n==k or k==0 or n==1:
return 1
if k==1:
return n
return pascal(n-1,k-1)+pascal(n-1,k)
跳舞的数字[Just for fun]
if __name__ == "__main__":
#depth = int(raw_input("pls enter the depth of pascal:"))
for depth in range(100):
lines = generatePascal(depth)
for i in range(depth):
print lines[i]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。