python输出倒立杨辉三角
时间: 2024-01-18 12:18:05 浏览: 128
以下是Python输出倒立杨辉三角的代码示例:
```python
def print_inverted_pascal_triangle(n):
triangle = []
for i in range(n):
row = [1] * (i + 1)
triangle.append(row)
for j in range(1, i):
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
for row in reversed(triangle):
print(' '.join(map(str, row)))
# 示例调用
print_inverted_pascal_triangle(5)
```
输出结果为:
```
1 4 6 4 1
1 3 3 1
1 2 1
1 1
1
```
相关问题
python中输出杨辉三角
可以使用嵌套列表来实现输出杨辉三角。以下是一个示例代码:
```python
def generate_pascal_triangle(num_rows):
triangle = []
for row_num in range(num_rows):
# 每一行开始和结尾都是1
row = [1] * (row_num + 1)
# 计算中间的数值
for j in range(1, row_num):
row[j] = triangle[row_num - 1][j - 1] + triangle[row_num - 1][j]
triangle.append(row)
return triangle
# 输出10层的杨辉三角
triangle = generate_pascal_triangle(10)
for row in triangle:
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]
```
python列表输出杨辉三角
以下是Python中使用列表输出杨辉三角的方法:
```python
def generate(numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
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
# 示例
print(generate(5))
```
该方法使用了一个二维列表来存储杨辉三角,其中每一行的首位和末位都为1,中间的数字通过上一行的相邻两个数字相加得到。通过循环生成每一行,最终返回整个杨辉三角的列表。
阅读全文