Python 中的帕斯卡三角?

问题描述 投票:0回答:1

我想用 python 打印帕斯卡三角形。

def generate_pascal_triangle(n):
    pascal_triangle = []
    for i in range(n):
        row = [1] * (i + 1)
        if i > 1:
            for j in range(1, i):
                row[j] = pascal_triangle[i - 1][j - 1] + pascal_triangle[i - 1][j]
        pascal_triangle.append(row)
    return pascal_triangle

# Change the value of 'n' to generate Pascal's Triangle of desired rows
n = 8
triangle = generate_pascal_triangle(n)

我无法得到结果,请帮我找出错误..

python pycharm
1个回答
0
投票

您的代码中没有“print”语句。如果你像这样修改你的代码,你将得到你的三角形:

def generate_pascal_triangle(n):
    pascal_triangle = []
    for i in range(n):
        row = [1] * (i + 1)
        if i > 1:
            for j in range(1, i):
                row[j] = pascal_triangle[i - 1][j - 1] + pascal_triangle[i - 1][j]

        # add your print statement here
        print(row)
        
        # if you only want to print the triangle, you don't have to append or return anything, you can also remove the two rows below   
        pascal_triangle.append(row)
    return pascal_triangle

# Change the value of 'n' to generate Pascal's Triangle of desired rows
n = 8
triangle = generate_pascal_triangle(n)
print(triangle)

© www.soinside.com 2019 - 2024. All rights reserved.