python求杨辉三角
时间: 2023-07-01 16:26:25 浏览: 77
好的,以下是Python代码实现杨辉三角:
```python
def generate_triangle(num_rows):
# 初始化杨辉三角
triangle = []
# 遍历每一行
for row_num in range(num_rows):
# 初始化当前行,并将第一个元素赋值为1
row = [1]
# 遍历当前行的元素,除了最后一个元素
for j in range(1, row_num):
# 计算当前元素的值,并加入当前行
row.append(triangle[row_num-1][j-1] + triangle[row_num-1][j])
# 最后一个元素也赋值为1
if(row_num > 0):
row.append(1)
# 将当前行加入杨辉三角
triangle.append(row)
return triangle
# 生成10行的杨辉三角
triangle = generate_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]
```
阅读全文