2016-09-26 10:28:43 +00:00
|
|
|
"""
|
2020-06-16 08:09:19 +00:00
|
|
|
This is a pure Python implementation of Dynamic Programming solution to the fibonacci
|
|
|
|
sequence problem.
|
2016-09-26 10:28:43 +00:00
|
|
|
"""
|
2016-09-26 10:26:23 +00:00
|
|
|
|
2016-09-26 10:38:40 +00:00
|
|
|
|
|
|
|
class Fibonacci:
|
2021-10-31 14:19:44 +00:00
|
|
|
def __init__(self) -> None:
|
|
|
|
self.sequence = [0, 1]
|
2016-09-26 10:26:23 +00:00
|
|
|
|
2021-10-31 14:19:44 +00:00
|
|
|
def get(self, index: int) -> list:
|
2019-10-09 19:20:19 +00:00
|
|
|
"""
|
2021-10-31 14:19:44 +00:00
|
|
|
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]
|
2019-10-09 19:20:19 +00:00
|
|
|
"""
|
2022-10-28 13:54:54 +00:00
|
|
|
if (difference := index - (len(self.sequence) - 2)) >= 1:
|
2021-10-31 14:19:44 +00:00
|
|
|
for _ in range(difference):
|
|
|
|
self.sequence.append(self.sequence[-1] + self.sequence[-2])
|
|
|
|
return self.sequence[:index]
|
2016-09-26 10:26:23 +00:00
|
|
|
|
|
|
|
|
2023-05-14 21:03:13 +00:00
|
|
|
def main() -> None:
|
2021-10-31 14:19:44 +00:00
|
|
|
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
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2021-10-31 14:19:44 +00:00
|
|
|
try:
|
|
|
|
index: int = int(prompt)
|
|
|
|
except ValueError:
|
|
|
|
print("Enter a number or 'exit'")
|
|
|
|
continue
|
2019-10-09 19:20:19 +00:00
|
|
|
|
2021-10-31 14:19:44 +00:00
|
|
|
print(fibonacci.get(index))
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|