Question
Write a Python module that solves a problem.
Answers
Answered by
GPT-4o mini
Sure! Let’s create a Python module that solves a common problem: calculating the nth Fibonacci number. The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1.
The nth Fibonacci number can be calculated using a few different methods, but for simplicity, we will implement an iterative approach as well as a recursive approach.
### Fibonacci Module
Here's how the Python module could look:
```python
# fibonacci.py
def fibonacci_iterative(n):
"""
Calculate the nth Fibonacci number using an iterative approach.
Args:
n (int): The index of the Fibonacci sequence.
Returns:
int: The nth Fibonacci number.
Raises:
ValueError: If n is less than 0.
"""
if n < 0:
raise ValueError("n must be a non-negative integer.")
elif 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
def fibonacci_recursive(n):
"""
Calculate the nth Fibonacci number using a recursive approach.
Args:
n (int): The index of the Fibonacci sequence.
Returns:
int: The nth Fibonacci number.
Raises:
ValueError: If n is less than 0.
"""
if n < 0:
raise ValueError("n must be a non-negative integer.")
elif n == 0:
return 0
elif n == 1:
return 1
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: python fibonacci.py <method: iterative|recursive> <n>")
sys.exit(1)
method = sys.argv[1].lower()
n = int(sys.argv[2])
if method == "iterative":
result = fibonacci_iterative(n)
elif method == "recursive":
result = fibonacci_recursive(n)
else:
print("Unknown method. Choose either 'iterative' or 'recursive'.")
sys.exit(1)
print(f"The {n}th Fibonacci number is: {result}")
```
### How to use the module
1. Save the code above into a file named `fibonacci.py`.
2. Open a terminal or command prompt.
3. Navigate to the directory where `fibonacci.py` is located.
4. Execute the script using one of the following commands:
For the iterative approach:
```bash
python fibonacci.py iterative 10
```
For the recursive approach:
```bash
python fibonacci.py recursive 10
```
Replace `10` with any non-negative integer `n` to calculate the nth Fibonacci number.
### Explanation
- The module defines two functions: `fibonacci_iterative` and `fibonacci_recursive` which calculate the nth Fibonacci number using iterative and recursive methods, respectively.
- It checks that the input is valid (non-negative integer) and raises a `ValueError` for invalid inputs.
- When the module is run directly, it accepts command-line arguments to specify the method and the desired Fibonacci number index.
Feel free to modify or expand upon this module as needed!
The nth Fibonacci number can be calculated using a few different methods, but for simplicity, we will implement an iterative approach as well as a recursive approach.
### Fibonacci Module
Here's how the Python module could look:
```python
# fibonacci.py
def fibonacci_iterative(n):
"""
Calculate the nth Fibonacci number using an iterative approach.
Args:
n (int): The index of the Fibonacci sequence.
Returns:
int: The nth Fibonacci number.
Raises:
ValueError: If n is less than 0.
"""
if n < 0:
raise ValueError("n must be a non-negative integer.")
elif 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
def fibonacci_recursive(n):
"""
Calculate the nth Fibonacci number using a recursive approach.
Args:
n (int): The index of the Fibonacci sequence.
Returns:
int: The nth Fibonacci number.
Raises:
ValueError: If n is less than 0.
"""
if n < 0:
raise ValueError("n must be a non-negative integer.")
elif n == 0:
return 0
elif n == 1:
return 1
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
if __name__ == "__main__":
import sys
if len(sys.argv) != 3:
print("Usage: python fibonacci.py <method: iterative|recursive> <n>")
sys.exit(1)
method = sys.argv[1].lower()
n = int(sys.argv[2])
if method == "iterative":
result = fibonacci_iterative(n)
elif method == "recursive":
result = fibonacci_recursive(n)
else:
print("Unknown method. Choose either 'iterative' or 'recursive'.")
sys.exit(1)
print(f"The {n}th Fibonacci number is: {result}")
```
### How to use the module
1. Save the code above into a file named `fibonacci.py`.
2. Open a terminal or command prompt.
3. Navigate to the directory where `fibonacci.py` is located.
4. Execute the script using one of the following commands:
For the iterative approach:
```bash
python fibonacci.py iterative 10
```
For the recursive approach:
```bash
python fibonacci.py recursive 10
```
Replace `10` with any non-negative integer `n` to calculate the nth Fibonacci number.
### Explanation
- The module defines two functions: `fibonacci_iterative` and `fibonacci_recursive` which calculate the nth Fibonacci number using iterative and recursive methods, respectively.
- It checks that the input is valid (non-negative integer) and raises a `ValueError` for invalid inputs.
- When the module is run directly, it accepts command-line arguments to specify the method and the desired Fibonacci number index.
Feel free to modify or expand upon this module as needed!