mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-12-18 01:00:15 +00:00
868c2fa0a8
* Removed doctest call * Removed 0 and 1 append to `fib_array` * Moved fibonacci sequence logic into `calculate` * Refactored `get` to generate missing numbers * Renamed `fib_array` to `sequence` * Renamed `number` to `index` * Refactored `get` to only return sequence to `index` * Moved main block into function * Added documentation to `get` * Added missing type hints * Fixed doctest error in `get` docstring * Moved calculate logic into get * Reformatted with black * Fixed wrong generation range
53 lines
1.3 KiB
Python
53 lines
1.3 KiB
Python
"""
|
|
This is a pure Python implementation of Dynamic Programming solution to the fibonacci
|
|
sequence problem.
|
|
"""
|
|
|
|
|
|
class Fibonacci:
|
|
def __init__(self) -> None:
|
|
self.sequence = [0, 1]
|
|
|
|
def get(self, index: int) -> list:
|
|
"""
|
|
Get the Fibonacci number of `index`. If the number does not exist,
|
|
calculate all missing numbers leading up to the number of `index`.
|
|
|
|
>>> Fibonacci().get(10)
|
|
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
|
|
>>> Fibonacci().get(5)
|
|
[0, 1, 1, 2, 3]
|
|
"""
|
|
difference = index - (len(self.sequence) - 2)
|
|
if difference >= 1:
|
|
for _ in range(difference):
|
|
self.sequence.append(self.sequence[-1] + self.sequence[-2])
|
|
return self.sequence[:index]
|
|
|
|
|
|
def main():
|
|
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 = Fibonacci()
|
|
|
|
while True:
|
|
prompt: str = input(">> ")
|
|
if prompt in {"exit", "quit"}:
|
|
break
|
|
|
|
try:
|
|
index: int = int(prompt)
|
|
except ValueError:
|
|
print("Enter a number or 'exit'")
|
|
continue
|
|
|
|
print(fibonacci.get(index))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|