python杨辉三角形居中
时间: 2024-03-04 19:47:23 浏览: 241
杨辉三角形是一个由数字构成的三角形,每个数字是上方两个数字之和。在Python中,可以使用循环和列表来生成杨辉三角形,并将其居中显示。以下是一个示例代码:
```python
def generate_pascal_triangle(num_rows):
triangle = []
for i in range(num_rows):
row = [1] * (i + 1)
if 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_pascal_triangle(triangle):
max_num_length = len(str(triangle[-1][len(triangle[-1]) // 2]))
for row in triangle:
row_str = ' '.join([str(num).center(max_num_length) for num in row])
print(row_str.center(len(row_str) + max_num_length))
num_rows = 5
triangle = generate_pascal_triangle(num_rows)
print_pascal_triangle(triangle)
```
运行以上代码,将会输出一个居中显示的5行杨辉三角形:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
阅读全文