python用列表实现杨辉三角形的前十行输出
时间: 2023-05-23 15:01:58 浏览: 117
用Python输出一个杨辉三角的例子
我可以回答这个问题。以下是python用列表实现杨辉三角形的前十行输出的代码:
```python
def generate(numRows):
triangle = []
for row_num in range(numRows):
# The first and last row elements are always 1.
row = [None for _ in range(row_num+1)]
row[0], row[-1] = 1, 1
# Each triangle element is equal to the sum of the elements
# above-and-to-the-left and above-and-to-the-right.
for j in range(1, len(row)-1):
row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j]
triangle.append(row)
return triangle
for row in generate(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]
```
阅读全文