chatgpt-4o-latest-20250326· OpenAI
LMArena Human Preference 140K
Write a Python function that calculates the Fibonacci sequence recursively and iteratively
- User
Write a Python function that calculates the Fibonacci sequence recursively and iteratively
- Assistant
Sure! Here's a Python implementation of the Fibonacci sequence using both recursive and iterative approaches:
def fibonacci_recursive(n): """ Calculate the nth Fibonacci number using recursion. """ if n <= 0: return 0 elif n == 1: return 1 else: return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2) def fibonacci_iterative(n): """ Calculate the nth Fibonacci number using iteration. """ if n <= 0: return 0 elif n == 1: return 1 a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b # Example usage: n = 10 print(f"Fibonacci number at position {n} (recursive): {fibonacci_recursive(n)}") print(f"Fibonacci number at position {n} (iterative): {fibonacci_iterative(n)}")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.