o3-mini· OpenAI LMArena Human Preference 140K
Implement a factorial function in Python.
- User
Implement a factorial function in Python.
- Assistant
Here's a simple implementation of a factorial function in Python using both a recursive and an iterative approach.
Recursive Implementation
def factorial_recursive(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") if n == 0 or n == 1: return 1 return n * factorial_recursive(n - 1) # Example usage: print(factorial_recursive(5)) # Output: 120Iterative Implementation
def factorial_iterative(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") result = 1 for i in range(1, n + 1): result *= i return result # Example usage: print(factorial_iterative(5)) # Output: 120Both functions check for negative inputs and raise a
ValueErrorif a negative number is provided, since the factorial is only defined for non-negative integers. You can use either version based on your preference or requirements.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.