记第一次没有独立做出来的题,杨辉三角

def triangles(n):
ret = [1]
i=0
while i<n:
yield ret
for i in range(1, len(ret)):
ret[i] = pre[i] + pre[i - 1]
ret.append(1)
pre = ret[:]
i+=1
for i,j in enumerate(triangles(6)):
print(' '*(6-i)+str(j))

注:如果需要使用列表中的前后元素进行运算时最好使用后面的元素倒推前面的元素,例如L[i]+L[i-1]因为for i in range(1,1)时不会出现索引越界,不需要额外进行一次异常处理,思路不容易被搞乱

猜你喜欢

转载自www.cnblogs.com/akuma233/p/8934543.html