|
1 | 1 | """ |
2 | | -This is a pure Python implementation of Dynamic Programming solution to the fibonacci |
3 | | -sequence problem. |
| 2 | +This is a pure Python implementation of a dynamic programming solution |
| 3 | +to generate the Fibonacci sequence. |
4 | 4 | """ |
5 | 5 |
|
| 6 | +from typing import List |
| 7 | + |
6 | 8 |
|
7 | 9 | class Fibonacci: |
8 | 10 | def __init__(self) -> None: |
9 | | - self.sequence = [0, 1] |
| 11 | + self.sequence: List[int] = [0, 1] |
10 | 12 |
|
11 | | - def get(self, index: int) -> list: |
| 13 | + def get(self, index: int) -> List[int]: |
12 | 14 | """ |
13 | | - Get the Fibonacci number of `index`. If the number does not exist, |
14 | | - calculate all missing numbers leading up to the number of `index`. |
| 15 | + Return the Fibonacci sequence up to the given index (exclusive). |
| 16 | +
|
| 17 | + Args: |
| 18 | + index: The number of Fibonacci values to generate. |
| 19 | +
|
| 20 | + Returns: |
| 21 | + A list of Fibonacci numbers up to the given index. |
| 22 | +
|
| 23 | + Raises: |
| 24 | + ValueError: If index is a negative integer. |
15 | 25 |
|
16 | 26 | >>> Fibonacci().get(10) |
17 | 27 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] |
18 | 28 | >>> Fibonacci().get(5) |
19 | 29 | [0, 1, 1, 2, 3] |
20 | 30 | """ |
| 31 | + if index < 0: |
| 32 | + raise ValueError("index must be a non-negative integer") |
| 33 | + |
21 | 34 | if (difference := index - (len(self.sequence) - 2)) >= 1: |
22 | 35 | for _ in range(difference): |
23 | 36 | self.sequence.append(self.sequence[-1] + self.sequence[-2]) |
| 37 | + |
24 | 38 | return self.sequence[:index] |
25 | 39 |
|
26 | 40 |
|
27 | 41 | def main() -> None: |
28 | 42 | print( |
29 | | - "Fibonacci Series Using Dynamic Programming\n", |
30 | | - "Enter the index of the Fibonacci number you want to calculate ", |
31 | | - "in the prompt below. (To exit enter exit or Ctrl-C)\n", |
32 | | - sep="", |
| 43 | + "Fibonacci Series Using Dynamic Programming\n" |
| 44 | + "Enter the number of Fibonacci values to generate.\n" |
| 45 | + "(Type 'exit' or press Ctrl-C to quit)\n" |
33 | 46 | ) |
| 47 | + |
34 | 48 | fibonacci = Fibonacci() |
35 | 49 |
|
36 | 50 | while True: |
37 | 51 | prompt: str = input(">> ") |
38 | | - if prompt in {"exit", "quit"}: |
| 52 | + |
| 53 | + if prompt.lower() in {"exit", "quit"}: |
39 | 54 | break |
40 | 55 |
|
41 | 56 | try: |
42 | | - index: int = int(prompt) |
43 | | - except ValueError: |
44 | | - print("Enter a number or 'exit'") |
45 | | - continue |
46 | | - |
47 | | - print(fibonacci.get(index)) |
| 57 | + index = int(prompt) |
| 58 | + print(fibonacci.get(index)) |
| 59 | + except ValueError as exc: |
| 60 | + print(f"Error: {exc}") |
48 | 61 |
|
49 | 62 |
|
50 | 63 | if __name__ == "__main__": |
|
0 commit comments