Generate a Python script to print the Fibonacci sequence.
- User
Generate a Python script to print the Fibonacci sequence.
Assistant
-
Core Problem: Generate the Fibonacci sequence where each number is the sum of the two preceding ones (F(n) = F(n-1) + F(n-2)), starting from 0 and 1.
-
Approaches to Consider:
- Iterative: O(n) time, O(1) space - efficient and straightforward
- Recursive: O(2^n) time - elegant but exponentially slow
- Generator: Memory-efficient for large sequences, Pythonic
- Memoized: Optimizes recursive approach to O(n)
-
Architectural Decisions:
- Use a generator pattern as the primary implementation - it's memory-efficient and follows Python best practices
- Include an iterative version as a simple alternative
- Add input validation for robustness
- Use command-line arguments for flexibility
- Handle edge cases (n=0, n=1, negative numbers)
-
Design Choices:
- Starting values: 0, 1 (modern standard definition)
- Parameter: number of terms to generate
- Output: space-separated sequence printed to stdout
Architectural Decisions
-
Generator Pattern: Using Python generators provides memory efficiency and laziness - we only compute values as needed.
-
Multiple Implementations: Providing both generator and iterative approaches demonstrates different techniques while offering flexibility.
-
Command-Line Interface: Using
argparsefor professional argument handling with validation and help text. -
Defensive Programming: Input validation ensures the program handles edge cases gracefully.
-
Modular Design: Separating the sequence generation logic from I/O makes the code testable and reusable.
Implementation
#!/usr/bin/env python3 """ Fibonacci Sequence Generator Generates and prints the Fibonacci sequence to a specified length. The sequence starts: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... Usage: python fibonacci.py [N] Examples: python fibonacci.py 10 # Print first 10 Fibonacci numbers python fibonacci.py # Print first 10 (default) """ import argparse from typing import Generator def fibonacci_generator(n: int) -> Generator[int, None, None]: """ Generate the first n Fibonacci numbers using a generator. This approach is memory-efficient as it yields one value at a time rather than storing the entire sequence in memory. Args: n: Number of Fibonacci numbers to generate Yields: The next Fibonacci number in the sequence """ if n <= 0: return a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b def fibonacci_iterative(n: int) -> list[int]: """ Generate the first n Fibonacci numbers using iteration. Simple approach that returns a complete list of the sequence. Args: n: Number of Fibonacci numbers to generate Returns: List containing the first n Fibonacci numbers """ if n <= 0: return [] if n == 1: return [0] sequence = [0, 1] for _ in range(2, n): sequence.append(sequence[-1] + sequence[-2]) return sequence def validate_input(n: int) -> None: """ Validate the input parameter. Args: n: Number to validate Raises: ValueError: If n is not a positive integer """ if not isinstance(n, int): raise ValueError("Input must be an integer") if n < 0: raise ValueError("Number of terms must be non-negative") def main(): """Main entry point for the Fibonacci sequence generator.""" parser = argparse.ArgumentParser( description="Generate the Fibonacci sequence", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: %(prog)s 15 Print first 15 Fibonacci numbers %(prog)s 1 Print just the first number (0) %(prog)s 0 Print nothing """ ) parser.add_argument( "n", type=int, nargs="?", default=10, help="Number of Fibonacci numbers to generate (default: 10)" ) args = parser.parse_args() try: validate_input(args.n) except ValueError as e: print(f"Error: {e}") return 1 # Use the generator approach for memory efficiency sequence = list(fibonacci_generator(args.n)) if sequence: print("Fibonacci sequence:") print(" ".join(map(str, sequence))) else: print("No terms to display.") return 0 if __name__ == "__main__": exit(main())
Example Output
$ python fibonacci.py 10 Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34 $ python fibonacci.py 5 Fibonacci sequence: 0 1 1 2 3 $ python fibonacci.py --help usage: fibonacci.py [-h] [n] Generate the Fibonacci sequence positional arguments: n Number of Fibonacci numbers to generate (default: 10) options: -h, --help show this help message and exit
Key Features
Feature Implementation Memory Efficiency Generator pattern yields one value at a time Input Validation Validates non-negative integers CLI Interface argparse with help text and defaults Type Hints Full type annotations for clarity Documentation Docstrings following Google style -