用python输出杨辉三角
时间: 2024-01-26 19:44:07 浏览: 53
可以使用以下代码来输出杨辉三角:
```python
def print_pascal_triangle(n):
triangle = [[1] * (i + 1) for i in range(n)]
for i in range(n):
for j in range(1, i):
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
for row in triangle:
print(" ".join(str(num) for num in row).center(n * 2))
```
调用`print_pascal_triangle(n)`即可输出$n$行的杨辉三角形式,例如:
```python
>>> print_pascal_triangle(5)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
相关问题
Python输出杨辉三角形
好的,以下是Python代码输出杨辉三角形:
```
n = int(input("请输入行数:"))
# 初始化二维数组
triangle = [[0 for col in range(n)] for row in range(n)]
# 设置第一列的值为1
for i in range(n):
triangle[i][0] = 1
# 填充剩余的值
for i in range(1, n):
for j in range(1, i+1):
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j]
# 输出杨辉三角形
for i in range(n):
for j in range(i+1):
print(triangle[i][j], end=" ")
print()
```
python输出杨辉三角
好的,以下是 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(' '.join(map(str, row)).center(n*2))
# 示例
print_triangle(6)
```
输出结果如下:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
其中 `generate_triangle(n)` 函数用于生成杨辉三角,`print_triangle(n)` 函数用于将其输出到屏幕上。
阅读全文