Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 30 additions & 17 deletions dynamic_programming/fibonacci.py
Original file line number Diff line number Diff line change
@@ -1,50 +1,63 @@
"""
This is a pure Python implementation of Dynamic Programming solution to the fibonacci
sequence problem.
This is a pure Python implementation of a dynamic programming solution
to generate the Fibonacci sequence.
"""

from typing import List

Check failure on line 6 in dynamic_programming/fibonacci.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

dynamic_programming/fibonacci.py:6:1: UP035 `typing.List` is deprecated, use `list` instead


class Fibonacci:
def __init__(self) -> None:
self.sequence = [0, 1]
self.sequence: List[int] = [0, 1]

Check failure on line 11 in dynamic_programming/fibonacci.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

dynamic_programming/fibonacci.py:11:24: UP006 Use `list` instead of `List` for type annotation

def get(self, index: int) -> list:
def get(self, index: int) -> List[int]:

Check failure on line 13 in dynamic_programming/fibonacci.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

dynamic_programming/fibonacci.py:13:34: UP006 Use `list` instead of `List` for type annotation
"""
Get the Fibonacci number of `index`. If the number does not exist,
calculate all missing numbers leading up to the number of `index`.
Return the Fibonacci sequence up to the given index (exclusive).

Args:
index: The number of Fibonacci values to generate.

Returns:
A list of Fibonacci numbers up to the given index.

Raises:
ValueError: If index is a negative integer.

>>> Fibonacci().get(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> Fibonacci().get(5)
[0, 1, 1, 2, 3]
"""
if index < 0:
raise ValueError("index must be a non-negative integer")

if (difference := index - (len(self.sequence) - 2)) >= 1:
for _ in range(difference):
self.sequence.append(self.sequence[-1] + self.sequence[-2])

return self.sequence[:index]


def main() -> None:
print(
"Fibonacci Series Using Dynamic Programming\n",
"Enter the index of the Fibonacci number you want to calculate ",
"in the prompt below. (To exit enter exit or Ctrl-C)\n",
sep="",
"Fibonacci Series Using Dynamic Programming\n"
"Enter the number of Fibonacci values to generate.\n"
"(Type 'exit' or press Ctrl-C to quit)\n"
)

fibonacci = Fibonacci()

while True:
prompt: str = input(">> ")
if prompt in {"exit", "quit"}:

if prompt.lower() in {"exit", "quit"}:
break

try:
index: int = int(prompt)
except ValueError:
print("Enter a number or 'exit'")
continue

print(fibonacci.get(index))
index = int(prompt)
print(fibonacci.get(index))
except ValueError as exc:
print(f"Error: {exc}")


if __name__ == "__main__":
Expand Down
Loading