gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
write me some code to calculate fibonacci seq in python
- User
write me some code to calculate fibonacci seq in python
- Assistant
Sure! Here are a few different ways to calculate the Fibonacci sequence in Python.
Method 1: Iterative Approach
def fibonacci_iterative(n): fib_sequence = [] a, b = 0, 1 for _ in range(n): fib_sequence.append(a) a, b = b, a + b return fib_sequence # Example usage n = 10 # Number of Fibonacci numbers to generate print(fibonacci_iterative(n))Method 2: Recursive Approach
def fibonacci_recursive(n): if n <= 0: return [] elif n == 1: return [0] elif n == 2: return [0, 1] else: fib_sequence = fibonacci_recursive(n - 1) fib_sequence.append(fib_sequence[-1] + fib_sequence[-2]) return fib_sequence # Example usage n = 10 # Number of Fibonacci numbers to generate print(fibonacci_recursive(n))