python快速打印杨辉三角
时间: 2023-05-30 21:01:26 浏览: 88
以下是Python代码,可以用于快速打印杨辉三角:
```
def generate(numRows):
triangle = []
for i in range(numRows):
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
n = int(input("请输入杨辉三角的行数:"))
result = generate(n)
for i in result:
print(i)
```
运行程序后,输入杨辉三角的行数,即可输出相应的杨辉三角。例如,输入5,输出的结果如下:
```
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
```
相关问题
python代码打印杨辉三角
好的,以下是Python代码打印杨辉三角:
```
def print_triangle(n):
row = [1]
for i in range(n):
print(row)
row = [1] + [row[j] + row[j+1] for j in range(len(row)-1)] + [1]
print_triangle(5)
```
输出结果如下:
```
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
```
python上打印杨辉三角
可以使用以下代码打印杨辉三角:
```python
def print_pascal_triangle(n):
# 初始化杨辉三角
pascal_triangle = [[1] * (i + 1) for i in range(n)]
# 计算杨辉三角中的每个元素
for i in range(n):
for j in range(1, i):
pascal_triangle[i][j] = pascal_triangle[i-1][j-1] + pascal_triangle[i-1][j]
# 打印杨辉三角
for row in pascal_triangle:
print(" ".join(str(num) for num in row).center(n*2))
# 测试
print_pascal_triangle(5)
```
输出结果为:
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
阅读全文