Factorial Practice Problem
This data science coding problem helps you practice Functions & Scope, factorial, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Functions & Scope.
- Problem ID: 82
- Problem key: 82-factorial
- URL: https://datacrack.app/solve/82-factorial
- Difficulty: easy
- Topic: Functions & Scope
- Module: Python Fundamentals
Problem Statement
# 🧩 Factorial
---
### 🎯 Goal
Factorial is the gateway to **recursion** — one of the most powerful problem-solving techniques. It also appears directly in combinatorics, probability, and statistics (permutations, combinations, Bayesian inference).
$$
n! = n \times (n-1) \times (n-2) \times \cdots \times 1
$$
$$
0! = 1 \quad \text{(by definition)}
$$
---
### 🔍 Recursive Thinking
Every recursive function has two parts:
1. **Base case** — the stopping condition (when do we stop calling ourselves?)
2. **Recursive case** — the problem reduced to a smaller version of itself
For factorial:
- Base case: `factorial(0) = 1` and `factorial(1) = 1`
- Recursive case: `factorial(n) = n * factorial(n - 1)`
---
### 💻 Task
Implement `factorial(n)` **recursively**.
---
### 📥 Input
- `n`: int — a non-negative integer
### 📤 Output
- int — n factorial
---
### 🧩 Starter Code
```python
def factorial(n):
"""
Compute n! recursively.
Args:
n (int): Non-negative integer
Returns:
int: n factorial
"""
# 🧠 TODO: Define the base case (n == 0 or n == 1)
# 🧠 TODO: Return n * factorial(n - 1) for the recursive case
pass
```
---
### 💡 Example
```python
factorial(5) # Expected: 120 (5 * 4 * 3 * 2 * 1)
factorial(0) # Expected: 1
factorial(10) # Expected: 3628800
```
---
### 🔑 Key Concepts
- Base case prevents infinite recursion
- `0! = 1` is a mathematical convention, not a coincidence — it's required for combinatorics formulas to work
- Factorial appears in `n choose k` = n! / (k! × (n-k)!)Starter Code
def factorial(n):
"""
Compute n! recursively.
Args:
n (int): Non-negative integer
Returns:
int: n factorial
"""
# 🧠 TODO: Define the base case (n == 0 or n == 1)
# 🧠 TODO: Return n * factorial(n - 1) for the recursive case
pass