python中输出杨辉三角
时间: 2024-01-18 10:42:21 浏览: 61
用Python输出一个杨辉三角的例子
可以使用嵌套列表来实现输出杨辉三角。以下是一个示例代码:
```python
def generate_pascal_triangle(num_rows):
triangle = []
for row_num in range(num_rows):
# 每一行开始和结尾都是1
row = [1] * (row_num + 1)
# 计算中间的数值
for j in range(1, row_num):
row[j] = triangle[row_num - 1][j - 1] + triangle[row_num - 1][j]
triangle.append(row)
return triangle
# 输出10层的杨辉三角
triangle = generate_pascal_triangle(10)
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]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
```
阅读全文