打印出n行杨辉三角python
时间: 2023-05-20 20:07:44 浏览: 88
当然可以,下面是Python代码:
```python
def generate_triangle(n):
triangle = []
for i in range(n):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle
def print_triangle(n):
triangle = generate_triangle(n)
for row in triangle:
print(row)
n = 5
print_triangle(n)
```
输出:
```
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
```
相关问题
python打印n行杨辉三角
好的,以下是 Python 打印 n 行杨辉三角的代码:
```python
n = int(input("请输入要打印的行数:"))
tri = [[1] * (i+1) for i in range(n)]
for i in range(n):
for j in range(i):
tri[i][j+1] = tri[i-1][j] + tri[i-1][j+1]
for i in range(n):
print(' '*(n-i-1), end='')
for j in range(i+1):
print(tri[i][j], end=' ')
print()
```
希望能帮到你!接下来还有什么其它问题吗?
打印10行杨辉三角python
以下是打印10行杨辉三角的 Python 代码:
```python
n = 10
triangle = []
for i in range(n):
row = [1] * (i+1)
for j in range(1, i):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
for row in triangle:
print(" ".join(str(num) for num in 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
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)