1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Pascal's Triangle for Python

Discussão em 'Python' iniciado por Stack, Novembro 21, 2025.

  1. Stack

    Stack Membro Participativo

    As a learning experience for Python, I am trying to code my own version of Pascal's triangle. It took me a few hours (as I am just starting), but I came out with this code:

    pascals_triangle = []

    def blank_list_gen(x):
    while len(pascals_triangle) < x:
    pascals_triangle.append([0])

    def pascals_tri_gen(rows):
    blank_list_gen(rows)
    for element in range(rows):
    count = 1
    while count < rows - element:
    pascals_triangle[count + element].append(0)
    count += 1
    for row in pascals_triangle:
    row.insert(0, 1)
    row.append(1)
    pascals_triangle.insert(0, [1, 1])
    pascals_triangle.insert(0, [1])

    pascals_tri_gen(6)

    for row in pascals_triangle:
    print(row)


    which returns

    [1]
    [1, 1]
    [1, 0, 1]
    [1, 0, 0, 1]
    [1, 0, 0, 0, 1]
    [1, 0, 0, 0, 0, 1]
    [1, 0, 0, 0, 0, 0, 1]
    [1, 0, 0, 0, 0, 0, 0, 1]


    However, I have no idea where to go from here. I have been banging my head against the wall for hours. I want to emphasize that I do NOT want you to do it for me; just push me in the right direction. As a list, my code returns

    [[1], [1, 1], [1, 0, 1], [1, 0, 0, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 1]]


    Thanks.

    EDIT: I took some good advice, and I completely rewrote my code, but I am now running into another problem. Here is my code.

    import math

    pascals_tri_formula = []

    def combination(n, r):
    return int((math.factorial(n)) / ((math.factorial(r)) * math.factorial(n - r)))

    def for_test(x, y):
    for y in range(x):
    return combination(x, y)

    def pascals_triangle(rows):
    count = 0
    while count <= rows:
    for element in range(count + 1):
    [pascals_tri_formula.append(combination(count, element))]
    count += 1

    pascals_triangle(3)

    print(pascals_tri_formula)


    However, I am finding that the output is a bit undesirable:

    [1, 1, 1, 1, 2, 1, 1, 3, 3, 1]


    How can I fix this?

    Continue reading...

Compartilhe esta Página