打印出 杨辉三角,形如:
# 期待输出: # [1] # [1, 1] # [1, 2, 1] # [1, 3, 3, 1] # [1, 4, 6, 4, 1] # [1, 5, 10, 10, 5, 1] # [1, 6, 15, 20, 15, 6, 1] # [1, 7, 21, 35, 35, 21, 7, 1] # [1, 8, 28, 56, 70, 56, 28, 8, 1] # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] 递归方式: def triList(n): L=[1] if n>1: cL=triList(n-1) for i,d in enumerate(cL): if i!=len(cL)-1: L.append(d+cL[i+1]) L.append(1) return L def triangles(n): i=1 while i<=n: yield triList(i) i+=1 return 'done' 生成器方式: def triangles(n): L=[1] i=1 while i<=n: if i>1: t=[L[x]+L[x+1] for x in range(i) if x+1<len(L)] L=[1] for d in t: L.append(d) L.append(1) yield L i+=1 return 'done' 执行: x = triangles(10) for g in x: print(g)