Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print Nth Row of Pascal Triangle

Print a zero-based Pascal-triangle row with recursive combinations. Students calculate each nCr and trace edge values that stop the recursive branching.

AdvancedPhase 6 - Category 4: Mathematical CombinationsExample 6 of 10
print-nth-row-of-pascal-triangle.py
1# Helper function
2def ncr(n, r):
3 if r == 0 or r == n:
4 return 1
5 return ncr(n - 1, r - 1) + ncr(n - 1, r)
6
7# Take n
8n = int(input("Enter row number: "))
9
10# Print row
11print(f"Row {n}:")
12for r in range(n + 1):
13 print(ncr(n, r), end=" ")
14print()

Output

Enter row number: 5
Row 5:
1 5 10 10 5 1

In this one

  • Index Pascal rows from zero
  • Reuse recursive combinations
  • Recognize repeated subproblems

How it works

  1. 1

    Read row number n.

  2. 2

    For every r from zero through n, call ncr.

  3. 3

    Print each returned row entry in order.

Edge cases

What does row zero contain?

What does row zero contain?

One entry: 1.

Are row numbers one-based?

Are row numbers one-based?

No. The top row is zero.

What's going on

The requested row n contains n + 1 entries. The outer loop calls ncr(n, r) for r from zero through n.

The helper returns one at either edge and adds the two parent combinations inside. Row three is 1 3 3 1. Pending additions use the call stack, and repeated subproblems make large rows expensive; this is not a memoized or iterative implementation.

What does row zero contain? One entry: 1.

Are row numbers one-based? No. The top row is zero.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What stops each recursive branch?

Pick an answer to check it.

Question 2

What does row zero contain?

Pick an answer to check it.

Questions people ask

What does row zero contain?

One entry: 1.

Are row numbers one-based?

No. The top row is zero.

What stops each recursive branch?

r == 0 or r == n.