# 帕斯卡三角形 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)
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]