使用python写出杨辉三角形的代码,至少使用3种方法

orange1年前 ⋅ 923 阅读
方法一:使用递归

```
def pascal_triangle(n):
    if n == 0:
        return []
    elif n == 1:
        return [[1]]
    else:
        row = [1]
        triangle = pascal_triangle(n - 1)
        last_row = triangle[-1]
        for i in range(len(last_row) - 1):
            row.append(last_row[i] + last_row[i+1])
        row += [1]
        triangle.append(row)
        return triangle

n = 5
triangle = pascal_triangle(n)
for row in triangle:
    print(row)
```

方法二:使用生成器

```
def pascal_triangle(n):
    row = [1]
    yield row
    for i in range(n - 1):
        row = [1] + [row[j] + row[j+1] for j in range(len(row)-1)] + [1]
        yield row

n = 5
for row in pascal_triangle(n):
    print(row)
```

方法三:使用列表推导式

```
n = 5
triangle = [[1]]
for i in range(1, n):
    row = [1] + [triangle[i-1][j] + triangle[i-1][j+1] for j in range(len(triangle[i-1])-1)] + [1]
    triangle.append(row)

for row in triangle:
    print(row)
```

全部评论: 0

    相关推荐