deepseek-v3-0324· DeepSeek LMArena Human Preference 140K
create a simple python program that contains recursion
- User
create a simple python program that contains recursion
- Assistant
Here’s a simple Python program that demonstrates recursion by calculating the factorial of a number (
n!).Factorial Using Recursion
The factorial of a number
n(denoted asn!) is the product of all positive integers from1ton.
For example:5! = 5 × 4 × 3 × 2 × 1 = 1200! = 1(by definition)
Python Code
def factorial(n): # Base case: 0! = 1 if n == 0: return 1 # Recursive case: n! = n × (n-1)! else: return n * factorial(n - 1) # Test the function number = 5 print(f"The factorial of {number} is {factorial(number)}")Output
The factorial of 5 is 120How It Works
- Base Case (
n == 0) → Stops recursion and returns1. - Recursive Case (
n > 0) → Callsfactorial(n - 1)and multiplies it byn.
Recursion Breakdown for
factorial(5)factorial(5) = 5 × factorial(4) = 5 × 4 × factorial(3) = 5 × 4 × 3 × factorial(2) = 5 × 4 × 3 × 2 × factorial(1) = 5 × 4 × 3 × 2 × 1 × factorial(0) = 5 × 4 × 3 × 2 × 1 × 1 = 120Alternative: Fibonacci Sequence (Another Recursion Example)
def fibonacci(n): if n <= 1: return n else: return fibonacci(n - 1) + fibonacci(n - 2) print(fibonacci(7)) # Output: 13 (0, 1, 1, 2, 3, 5, 8, 13)Would you like another recursion example (e.g., binary search, tree traversal)? 😊
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.