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:
|
2016-09-26 10:26:23 +00:00
|
|
|
def __init__(self, N=None):
|
2017-04-11 22:10:52 +00:00
|
|
|
self.fib_array = []
|
2016-09-26 10:26:23 +00:00
|
|
|
if N:
|
2016-09-26 10:38:40 +00:00
|
|
|
N = int(N)
|
2017-04-11 22:10:52 +00:00
|
|
|
self.fib_array.append(0)
|
|
|
|
self.fib_array.append(1)
|
2016-09-26 10:26:23 +00:00
|
|
|
for i in range(2, N + 1):
|
2017-04-11 22:10:52 +00:00
|
|
|
self.fib_array.append(self.fib_array[i - 1] + self.fib_array[i - 2])
|
2017-04-12 13:45:56 +00:00
|
|
|
elif N == 0:
|
2017-04-11 22:10:52 +00:00
|
|
|
self.fib_array.append(0)
|
2019-10-09 19:20:19 +00:00
|
|
|
print(self.fib_array)
|
2016-09-26 10:26:23 +00:00
|
|
|
|
|
|
|
def get(self, sequence_no=None):
|
2019-10-09 19:20:19 +00:00
|
|
|
"""
|
|
|
|
>>> Fibonacci(5).get(3)
|
|
|
|
[0, 1, 1, 2, 3, 5]
|
|
|
|
[0, 1, 1, 2]
|
|
|
|
>>> Fibonacci(5).get(6)
|
|
|
|
[0, 1, 1, 2, 3, 5]
|
|
|
|
Out of bound.
|
|
|
|
>>> Fibonacci(5).get(-1)
|
|
|
|
[0, 1, 1, 2, 3, 5]
|
|
|
|
[]
|
|
|
|
"""
|
2020-03-04 12:40:28 +00:00
|
|
|
if sequence_no is not None:
|
2016-09-26 10:26:23 +00:00
|
|
|
if sequence_no < len(self.fib_array):
|
2019-10-05 05:14:13 +00:00
|
|
|
return print(self.fib_array[: sequence_no + 1])
|
2016-09-26 10:26:23 +00:00
|
|
|
else:
|
|
|
|
print("Out of bound.")
|
|
|
|
else:
|
2017-04-11 22:10:52 +00:00
|
|
|
print("Please specify a value")
|
2016-09-26 10:26:23 +00:00
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2016-09-26 10:26:23 +00:00
|
|
|
print("\n********* Fibonacci Series Using Dynamic Programming ************\n")
|
|
|
|
print("\n Enter the upper limit for the fibonacci sequence: ", end="")
|
|
|
|
try:
|
2019-08-19 13:37:49 +00:00
|
|
|
N = int(input().strip())
|
2016-09-26 10:26:23 +00:00
|
|
|
fib = Fibonacci(N)
|
|
|
|
print(
|
2019-08-19 13:37:49 +00:00
|
|
|
"\n********* Enter different values to get the corresponding fibonacci "
|
2019-10-05 05:14:13 +00:00
|
|
|
"sequence, enter any negative number to exit. ************\n"
|
|
|
|
)
|
2016-09-26 10:26:23 +00:00
|
|
|
while True:
|
2016-09-26 10:38:40 +00:00
|
|
|
try:
|
2019-08-19 13:37:49 +00:00
|
|
|
i = int(input("Enter value: ").strip())
|
2016-09-26 10:38:40 +00:00
|
|
|
if i < 0:
|
|
|
|
print("\n********* Good Bye!! ************\n")
|
|
|
|
break
|
|
|
|
fib.get(i)
|
|
|
|
except NameError:
|
|
|
|
print("\nInvalid input, please try again.")
|
2016-09-26 10:26:23 +00:00
|
|
|
except NameError:
|
|
|
|
print("\n********* Invalid input, good bye!! ************\n")
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2019-10-09 19:20:19 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|