project1/fib.py

37 lines
1.0 KiB
Python
Raw Normal View History

2023-11-08 09:02:33 +00:00
"""A demo module implementing fib."""
2023-11-08 08:17:37 +00:00
import argparse
2023-11-08 09:33:30 +00:00
import logging
logger = logging.getLogger()
2023-11-08 08:17:37 +00:00
def parse_args():
2023-11-08 09:02:33 +00:00
"""Parse command line arguments."""
2023-11-08 08:17:37 +00:00
parser = argparse.ArgumentParser(description="Compute fibonacci sequence numbers.")
parser.add_argument("n", type=int, help="To compute the nth element of fib.")
2023-11-08 09:33:30 +00:00
parser.add_argument("-v", "--verbose", action="count", help="Be verbose", default=0)
2023-11-08 08:17:37 +00:00
return parser.parse_args()
2023-11-08 09:02:33 +00:00
def fib(n: int) -> int:
"""Return the *n*th element in the Fibonacci sequence."""
2023-11-08 08:17:37 +00:00
a, b = 1, 1
2023-11-08 09:33:30 +00:00
if n < 0:
logger.error("It'll go wrong with a negative number.")
logger.info(f"In fib, starting with: {a}, {b}")
2023-11-08 08:17:37 +00:00
for _ in range(n):
2023-11-08 09:33:30 +00:00
logger.debug(f"In fib, loop {_} with: {a}, {b}")
2023-11-08 08:17:37 +00:00
a, b = b, a + b
return a
2023-11-08 09:02:33 +00:00
def main() -> None:
"""The module entry point."""
2023-11-08 08:17:37 +00:00
args = parse_args()
2023-11-08 09:33:30 +00:00
logging.basicConfig(level=[logging.ERROR, logging.INFO, logging.DEBUG][args.verbose])
2023-11-08 08:17:37 +00:00
print(fib(args.n))
if __name__ == "__main__":
main()