Print Nth Row of Pascal Triangle

Print nth row of Pascal triangle.

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

What's going on

Use nCr formula to calculate each element.

Key Concepts:

nth row has n+1 elements
Element at position r is nCr
Use recursive formula