59 lines
1.3 KiB
Python
59 lines
1.3 KiB
Python
#!/usr/bin/env python3
|
|
"""Fibonacci sequence calculator with colored output."""
|
|
|
|
import argparse
|
|
import sys
|
|
|
|
# ANSI color codes
|
|
GREEN = "\033[32m"
|
|
CYAN = "\033[36m"
|
|
RED = "\033[31m"
|
|
RESET = "\033[0m"
|
|
|
|
|
|
def fibonacci(n: int) -> int:
|
|
"""Return the nth Fibonacci number (0-indexed).
|
|
|
|
fibonacci(0) = 0
|
|
fibonacci(1) = 1
|
|
fibonacci(2) = 1
|
|
fibonacci(3) = 2
|
|
...
|
|
"""
|
|
if n < 0:
|
|
raise ValueError(f"n must be non-negative, got {n}")
|
|
if n == 0:
|
|
return 0
|
|
if n == 1:
|
|
return 1
|
|
|
|
a, b = 0, 1
|
|
for _ in range(2, n + 1):
|
|
a, b = b, a + b
|
|
return b
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="Fibonacci sequence calculator")
|
|
parser.add_argument("n", type=int, help="The position n in the Fibonacci sequence")
|
|
parser.add_argument("--output", "-o", help="Write output to a file instead of stdout")
|
|
args = parser.parse_args()
|
|
|
|
try:
|
|
result = fibonacci(args.n)
|
|
except ValueError as e:
|
|
print(f"{RED}Error: {e}{RESET}")
|
|
sys.exit(1)
|
|
|
|
output_line = f"{CYAN}fibonacci({args.n}){RESET} {GREEN}={RESET} {GREEN}{result}{RESET}"
|
|
|
|
if args.output:
|
|
with open(args.output, "w") as f:
|
|
f.write(output_line + "\n")
|
|
else:
|
|
print(output_line)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|