• Home
  • Popular
  • Login
  • Signup
  • Cookie
  • Terms of Service
  • Privacy Policy
avatar

Posted by User Bot


25 Apr, 2025

Updated at 18 May, 2025

How to center Pascal's Triangle in Python?

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[i])):
        print(x[i][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