In Pascal's triangle, each row starts and ends with 1, and every other number is the sum of the two numbers above it. Row 4 (counting the top row as row 0) is 1 4 6 4 1, because 1 + 3 = 4, 3 + 3 = 6 and 3 + 1 = 4.
The program
python
rows = int(input("Number of rows: ")) row = [1] for _ in range(rows): print(" ".join(str(n) for n in row)) middle = [row[j] + row[j + 1] for j in range(len(row) - 1)] row = [1] + middle + [1]
Typed in this example: 6. Press Run to type your own.
output
Number of rows: 6 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
How it works
rowholds the current row as a list. It starts as[1].- After printing a row, the program builds the next one.
row[j] + row[j + 1]adds each pair of neighbours. For[1, 3, 3, 1]the pairs give[4, 6, 4]. - Putting a 1 at each end gives the new row:
[1, 4, 6, 4, 1]. - For row
[1]there are no pairs, somiddleis empty and the next row is[1, 1].
A centred triangle with math.comb()
The number in row i, position k (both counted from 0) is the number of ways to choose k items from i. math.comb(i, k) calculates it directly, so each value can be found without the row above it:
python
import math rows = 5 lines = [] for i in range(rows): lines.append(" ".join(str(math.comb(i, k)) for k in range(i + 1))) width = len(lines[-1]) for line in lines: print(line.center(width).rstrip())
output
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1
- The program builds all the lines first, so it knows the width of the last one.
line.center(width)adds spaces on both sides to centre the line.rstrip()removes the spaces on the right, which are not needed.- Once the numbers have two or more digits (from row 5, with 10), the rows have different widths and the triangle shape becomes uneven.