Search code examples
pythonpython-3.x

How to build a pascal triangle


i am trying to build a pascal triangle but output is not as expected i want output as

enter image description here

triangle = []

for i in range(num_rows):
row = [1] * (i + 1)
for j in range(1, i):
row[j] = triangle[i - 1][j - 1] + triangle[i - 1][j]
triangle.append(row)

return triangle

def print_pascals_triangle(triangle):
for row in triangle:
print(" ".join(map(str, row)))

try:
num_rows = int(input("Enter the number of rows for Pascal's Triangle: "))
if num_rows <= 0:
print("Please enter a positive integer.")
else:
pascals_triangle = generate_pascals_triangle(num_rows)
print_pascals_triangle(pascals_triangle)
except ValueError:
print("Invalid input. Please enter a valid integer.")

My output


Solution

  • Calculation of the triangle is trivial. Output format can be performed with the aid of str.center() [ Thanks to @AKX for pointing that out ]

    def pascal(n: int) -> list:
        r = []
    
        for i in range(1, n+1):
            row = [c := 1]
            for j in range(1, i):
                row.append(c := c * (i - j) // j)
            r.append(" ".join(map(str, row)))
    
        return r
    
    if p := pascal(8):
        w = len(p[-1])
        for row in p:
            print(row.center(w))
    

    Output:

             1
            1 1
           1 2 1
          1 3 3 1
         1 4 6 4 1
       1 5 10 10 5 1
     1 6 15 20 15 6 1
    1 7 21 35 35 21 7 1