打印出n行杨辉三角python
时间: 2023-05-20 17:07:44 浏览: 105
当然可以,下面是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]
```
相关问题
打印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
```
写一个打印n行杨辉三角的python代码
以下是打印n行杨辉三角的Python代码:
```python
n = int(input("请输入要打印的行数:"))
# 初始化杨辉三角
triangle = [[1]]
# 循环打印每一行
for i in range(1, n):
row = [1] # 每一行的第一个数为1
for j in range(1, i):
# 当前数等于上一行的两个数之和
num = triangle[i-1][j-1] + triangle[i-1][j]
row.append(num)
row.append(1) # 每一行的最后一个数为1
triangle.append(row)
# 打印杨辉三角
for i in range(n):
print(" "*(n-i), end="")
for j in range(i+1):
print(triangle[i][j], end=" ")
print()
```
运行结果:
```
请输入要打印的行数:8
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
```
阅读全文