Python计算并输出前十行杨辉三角形
时间: 2024-02-02 17:40:20 浏览: 65
利用Python编程实现打印杨辉三角输出,附源码
以下是Python代码:
```python
def generate_next_row(row):
result = [1]
for i in range(len(row) - 1):
result.append(row[i] + row[i + 1])
result.append(1)
return result
def generate_pascal_triangle(num_rows):
pascal_triangle = []
curr_row = [1]
for i in range(num_rows):
pascal_triangle.append(curr_row)
curr_row = generate_next_row(curr_row)
return pascal_triangle
def print_pascal_triangle(num_rows):
pascal_triangle = generate_pascal_triangle(num_rows)
for row in pascal_triangle:
print(row)
print_pascal_triangle(10)
```
输出结果:
```
[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]
```
阅读全文