Python打印杨辉三角
时间: 2023-08-14 12:31:35 浏览: 84
好的,以下是Python打印杨辉三角的代码:
```python
def yanghui_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(triangle):
max_num = triangle[-1][len(triangle[-1]) // 2]
max_digits = len(str(max_num))
for row in triangle:
row_str = ' '.join([str(num).rjust(max_digits) for num in row])
print(row_str.center(max_digits*len(row)))
n = 6
triangle = yanghui_triangle(n)
print_triangle(triangle)
```
运行结果:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
```
阅读全文