forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibonacci.py
54 lines (47 loc) · 1.76 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
52
53
54
"""
This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem.
"""
from __future__ import print_function
class Fibonacci:
def __init__(self, N=None):
self.fib_array = []
if N:
N = int(N)
self.fib_array.append(0)
self.fib_array.append(1)
for i in range(2, N + 1):
self.fib_array.append(self.fib_array[i - 1] + self.fib_array[i - 2])
elif N == 0:
self.fib_array.append(0)
def get(self, sequence_no=None):
if sequence_no != None:
if sequence_no < len(self.fib_array):
return print(self.fib_array[:sequence_no + 1])
else:
print("Out of bound.")
else:
print("Please specify a value")
if __name__ == '__main__':
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
try:
raw_input # Python 2
except NameError:
raw_input = input # Python 3
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
try:
N = eval(raw_input().strip())
fib = Fibonacci(N)
print(
"\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n")
while True:
print("Enter value: ", end=" ")
try:
i = eval(raw_input().strip())
if i < 0:
print("\n********* Good Bye!! ************\n")
break
fib.get(i)
except NameError:
print("\nInvalid input, please try again.")
except NameError:
print("\n********* Invalid input, good bye!! ************\n")