"""
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]
"""
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 = 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()
In mathematics, the Fibonacci numbers commonly denoted F(n), form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. The Sequence looks like this:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]
Finding
N-th
member of this sequence would be useful in many Applications:
science including high energy physics, quantum mechanics, Cryptography and Coding.
Find 8-th
member of Fibonacci
| F(n+1) F(n) |
| F(n) F(n-1)|
Calculate matrix^1
| 1 1 |
| 1 0 |
Calculate matrix^2
| 2 1 |
| 1 1 |
Calculate matrix^4
| 5 3 |
| 3 2 |
Calculate matrix^8
| 34 21 |
| 21 13 |
F(8)=21