python 打印出杨辉三角形前十行。
时间: 2023-09-12 10:13:39 浏览: 94
输出杨辉三角的前10行
好的,下面是 Python 代码实现:
```python
def generate_triangle(n):
# 初始化第一行
triangle = [[1]]
for i in range(1, n):
# 上一行
prev_row = triangle[-1]
# 当前行
curr_row = [1]
# 计算中间的数
for j in range(1, i):
curr_row.append(prev_row[j - 1] + prev_row[j])
# 最后一个数
curr_row.append(1)
# 添加到杨辉三角
triangle.append(curr_row)
return triangle
# 打印前十行
for row in generate_triangle(10):
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]
```
阅读全文