方法一:
triangle = [[1], [1, 1]]
n = 6
for i in range(2, 6):
pre = triangle[i - 1]
cur = [1]
for j in range(len(pre)-1):
cur.append(pre[j] + pre[j + 1])
cur.append(1)
triangle.append(cur)
print(triangle)
方法二(根据两边对称计算一半数据即可):
triangle = [[1], [1, 1]]
n = 6
for i in range(2, 6):
pre = triangle[i - 1]
cur_len = len(pre) + 1
cur = [1] + [0] *(cur_len - 2) + [1]
limit = cur_len//2 if not cur_len % 2 else (cur_len//2 + 1)
for j in range(1, limit):
val = pre[j-1] + pre[j]
cur[j] = val
cur[-j-1] = val
triangle.append(cur)
print(triangle)