用python打印杨辉三角
时间: 2023-11-19 09:05:27 浏览: 32
python之打印杨辉三角
下面是用 Python 打印杨辉三角的代码:
```python
def print_pascal_triangle(n):
triangle = []
for i in range(n):
row = []
for j in range(i+1):
if j == 0 or j == i:
row.append(1)
else:
row.append(triangle[i-1][j-1] + triangle[i-1][j])
triangle.append(row)
for row in triangle:
print(' '.join([str(elem) for elem in row]))
# 测试
print_pascal_triangle(5)
```
输出结果:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
阅读全文