方法一:迭代
def triangle_1(x):
"""
:param x: 需要生成的杨辉三角行数
:return:
"""
triangle = [[1], [1, 1]] # 初始化杨辉三角
n = 3 # 从第三行开始计数,逐行添加
while n <= x:
for i in range(0, n-1):
if i == 0:
# 添加初始列表[1,1],杨辉三角每行的首位和末位必为1
triangle.append([1, 1])
else:
# 逐位计算,并插入初始列表中
triangle[n-1].insert(i, triangle[n - 2][i] + triangle[n - 2][i - 1])
n += 1
return triangle
x = 11
triangle = triangle_1(x)
# 遍历结果,逐行打印
for i in range(x):
print(' '.join(str(triangle[i])).center(100)) # 转为str,居中显示