写一个求解杨辉三角形的Python程序,使用过 程调用的递归方法实现,输出杨辉三角形的前8 行
时间: 2024-03-26 09:41:56 浏览: 78
用Python输出一个杨辉三角的例子
好的,下面是使用递归方法实现杨辉三角形的 Python 程序,可以输出前 8 行:
```python
def pascal_triangle(n):
if n == 0:
return []
elif n == 1:
return [[1]]
else:
new_row = [1]
last_triangle = pascal_triangle(n-1)
last_row = last_triangle[-1]
for i in range(len(last_row)-1):
new_row.append(last_row[i] + last_row[i+1])
new_row += [1]
return last_triangle + [new_row]
# 输出前 8 行杨辉三角形
for row in pascal_triangle(8):
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]
```
阅读全文