[Python] How to center Pascal's Triangle in Python?

Discussão em 'Python' iniciado por Stack, Abril 25, 2025.

  1. Stack

    Stack Membro Participativo

    I need to print Pascal's Triangle as pyramid. I can only get it to print as a right triangle. I've looked at other questions on here asking the same thing, but can't figure out how to apply it to my code:

    def comb(k,n):
    ans = 1
    if (k > n//2):
    k = n-k
    for i in range(k):
    ans *= (n-i)
    ans //= (i+1)
    return ans

    def printPascal(n):
    x = []

    for row in range(n):
    arr = []
    for i in range (row + 1):
    arr.append(comb(i, row))
    x.append(arr)
    return x

    n = eval(input("How many rows should there be [3-8]? "))

    x = printPascal(n)

    for i in range(len(x)):
    for j in range(len(x)):
    print(x[j], end=" ")
    print()


    I saw the center method as an option, but can't figure out how to determine the maximum width based on the final row

    Continue reading...

Compartilhe esta Página