Print Nth Row of Pascal Triangle

Print nth row of Pascal triangle.

Logic BuildingAdvanced
Logic Building
# Helper function
def ncr(n, r):
    if r == 0 or r == n:
        return 1
    return ncr(n - 1, r - 1) + ncr(n - 1, r)

# Take n
n = int(input("Enter row number: "))

# Print row
print(f"Row {n}:")
for r in range(n + 1):
    print(ncr(n, r), end=" ")
print()

Output

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

Use nCr formula to calculate each element.

Key Concepts:

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