diff options
| author | Munyoki Kilyungi (aider) | 2025-02-26 17:32:10 +0300 |
|---|---|---|
| committer | BonfaceKilz | 2025-03-04 15:48:10 +0300 |
| commit | 280c5e97d21501c03f672ed3576ae3eddfc76420 (patch) | |
| tree | c4189592795caf0e117136ad0c280b9b19fd7d5f /scripts/fibonacci.py | |
| parent | e7baf1a4cf05a4e7794a6531c92d367fcd8f1651 (diff) | |
| download | genenetwork3-280c5e97d21501c03f672ed3576ae3eddfc76420.tar.gz | |
feat: Add Python implementation of Fibonacci number calculation
Diffstat (limited to 'scripts/fibonacci.py')
| -rw-r--r-- | scripts/fibonacci.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/scripts/fibonacci.py b/scripts/fibonacci.py new file mode 100644 index 0000000..0ee6afe --- /dev/null +++ b/scripts/fibonacci.py @@ -0,0 +1,42 @@ +""" +This module provides a function to calculate the nth Fibonacci number using an iterative approach. +""" + +def fibonacci(n: int) -> int: + """ + Calculate the nth Fibonacci number. + + The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. + Typically starting with 0 and 1. + + Args: + n (int): The position in the Fibonacci sequence to calculate. Must be a non-negative integer. + + Returns: + int: The nth Fibonacci number. + + Raises: + ValueError: If n is not a non-negative integer. + """ + if not isinstance(n, int): + raise ValueError("Input must be an integer.") + if n < 0: + raise ValueError("Input must be a non-negative integer.") + if 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 + +if __name__ == "__main__": + # Example usage: + try: + position = 10 + result = fibonacci(position) + print(f"The {position}th Fibonacci number is: {result}") + except ValueError as e: + print(f"Error: {e}") |
