Skip to content

Commit ddc0678

Browse files
committed
Fix input validation, typing, and documentation in Fibonacci DP example
1 parent 2c15b8c commit ddc0678

File tree

1 file changed

+30
-17
lines changed

1 file changed

+30
-17
lines changed

dynamic_programming/fibonacci.py

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,63 @@
11
"""
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.
44
"""
55

6+
from typing import List
7+
68

79
class Fibonacci:
810
def __init__(self) -> None:
9-
self.sequence = [0, 1]
11+
self.sequence: List[int] = [0, 1]
1012

11-
def get(self, index: int) -> list:
13+
def get(self, index: int) -> List[int]:
1214
"""
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.
1525
1626
>>> Fibonacci().get(10)
1727
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
1828
>>> Fibonacci().get(5)
1929
[0, 1, 1, 2, 3]
2030
"""
31+
if index < 0:
32+
raise ValueError("index must be a non-negative integer")
33+
2134
if (difference := index - (len(self.sequence) - 2)) >= 1:
2235
for _ in range(difference):
2336
self.sequence.append(self.sequence[-1] + self.sequence[-2])
37+
2438
return self.sequence[:index]
2539

2640

2741
def main() -> None:
2842
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"
3346
)
47+
3448
fibonacci = Fibonacci()
3549

3650
while True:
3751
prompt: str = input(">> ")
38-
if prompt in {"exit", "quit"}:
52+
53+
if prompt.lower() in {"exit", "quit"}:
3954
break
4055

4156
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}")
4861

4962

5063
if __name__ == "__main__":

0 commit comments

Comments
 (0)