Write me a recursive function in python with a test
- User
Write me a recursive function in python with a test
- Assistant
Sure, here's a simple recursive function in Python to calculate the factorial of a given number. I'll also provide a test for the function.
pythondef factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) def test_factorial(): assert factorial(0) == 1 assert factorial(1) == 1 assert factorial(5) == 120 if __name__ == "__main__": test_factorial() print(factorial(6)) # Output: 720In this example, the function takes a number as its argument and returns the factorial of . The function uses a base case where if the input is 0 or 1, the function directly returns 1. Otherwise, it recursively calls itself with the argument and multiplies the result by .
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.