用python语言写一个程序,题目:打印杨辉三角(用二维列表存储) 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、先用二维列表存储 2、然后打印二维列表(格式控制可自由发挥)
时间: 2024-01-02 08:03:52 浏览: 27
好的,以下是用Python语言编写的程序,可以打印出指定行数的杨辉三角,存储在一个二维列表中:
```python
def yanghui_triangle(n):
triangle = [[1] * (i+1) for i in range(n)]
for i in range(2, n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
return triangle
def print_triangle(triangle):
for row in triangle:
print(" ".join(str(num) for num in row).center(80))
n = int(input("请输入要打印的杨辉三角的行数: "))
triangle = yanghui_triangle(n)
print_triangle(triangle)
```
运行程序后,你可以输入要打印的杨辉三角的行数,程序会先用二维列表存储杨辉三角,然后再按照指定格式打印出来。你可以根据需要自由发挥格式控制,程序中使用了字符串的 `center()` 方法来居中对齐输出。
相关问题
题目:打印杨辉三角(用二维列表存储) 1 1 1 > > 2 3 1 1 3 1 1 1 5 5 1 1 6 4 10 10 6 15 20 15 7 21 353521 1 6 1 7 1 要求: 1) 先用二雒列表存儲 2) 然后打印二维列表(格式控制可自由发挥)
以下是 Python 代码实现:
```python
n = int(input("请输入要打印的行数:"))
# 初始化二维列表
triangle = [[1] * (i+1) for i in range(n)]
# 计算杨辉三角
for i in range(2, n):
for j in range(1, i):
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
# 打印杨辉三角
for row in triangle:
for num in row:
print(num, end=' ')
print()
```
输出结果:
```
请输入要打印的行数:7
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
```
python打印杨辉三角(用二维列表存储)
好的,以下是Python代码实现杨辉三角(使用二维列表存储):
```python
def generate(numRows):
triangle = []
for i in range(numRows):
row = [None for _ in range(i+1)]
row[0], row[-1] = 1, 1
for j in range(1, len(row)-1):
row[j] = triangle[i-1][j-1] + triangle[i-1][j]
triangle.append(row)
return triangle
n = 5
result = generate(n)
for i in range(n):
print(' '*(n-i), end='')
for j in range(i+1):
print(result[i][j], end=' ')
print()
```
其中,generate函数用于生成杨辉三角的二维列表,n表示杨辉三角的行数,result存储了生成的杨辉三角,最后使用两层for循环打印输出杨辉三角。
相关推荐
![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)