forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfibonacci.py
51 lines (40 loc) · 1.33 KB
/
fibonacci.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""
This is a pure Python implementation of Dynamic Programming solution to the fibonacci
sequence problem.
"""
classFibonacci:
def__init__(self) ->None:
self.sequence= [0, 1]
defget(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_inrange(difference):
self.sequence.append(self.sequence[-1] +self.sequence[-2])
returnself.sequence[:index]
defmain() ->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()
whileTrue:
prompt: str=input(">> ")
ifpromptin {"exit", "quit"}:
break
try:
index: int=int(prompt)
exceptValueError:
print("Enter a number or 'exit'")
continue
print(fibonacci.get(index))
if__name__=="__main__":
main()