用Python,输出7行的杨辉三角
时间: 2023-06-13 15:03:44 浏览: 104
用Python输出一个杨辉三角的例子
可以使用两个列表来保存杨辉三角上一行和当前行的元素,然后根据上一行的元素计算当前行的元素。以下是实现代码:
```python
def generate_pascal_triangle(num_rows):
triangle = []
for i in range(num_rows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle
# 输出7行的杨辉三角
triangle = generate_pascal_triangle(7)
for row in triangle:
print(row)
```
输出结果:
```
[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]
```
阅读全文