|
| 1 | +""" |
| 2 | +This is a pure Python implementation of Dynamic Programming solution to the fibonacci sequence problem. |
| 3 | +""" |
| 4 | +class Fibonacci: |
| 5 | + |
| 6 | + def __init__(self, N=None): |
| 7 | + if N: |
| 8 | + self.fib_array = [0] * (N + 1) |
| 9 | + self.fib_array[0] = 0 |
| 10 | + self.fib_array[1] = 1 |
| 11 | + for i in range(2, N + 1): |
| 12 | + self.fib_array[i] = self.fib_array[ |
| 13 | + i - 1] + self.fib_array[i - 2] |
| 14 | + else: |
| 15 | + self.fib_array = [None] * (N + 1) |
| 16 | + |
| 17 | + def get(self, sequence_no=None): |
| 18 | + if sequence_no: |
| 19 | + if sequence_no < len(self.fib_array): |
| 20 | + return print(self.fib_array[:sequence_no]) |
| 21 | + else: |
| 22 | + print("Out of bound.") |
| 23 | + else: |
| 24 | + print("Please specify the a value") |
| 25 | + |
| 26 | + |
| 27 | +if __name__ == '__main__': |
| 28 | + import sys |
| 29 | + |
| 30 | + print("\n********* Fibonacci Series Using Dynamic Programming ************\n") |
| 31 | + # For python 2.x and 3.x compatibility: 3.x has not raw_input builtin |
| 32 | + # otherwise 2.x's input builtin function is too "smart" |
| 33 | + if sys.version_info.major < 3: |
| 34 | + input_function = raw_input |
| 35 | + else: |
| 36 | + input_function = input |
| 37 | + |
| 38 | + print("\n Enter the upper limit for the fibonacci sequence: ", end="") |
| 39 | + try: |
| 40 | + N = eval(input()) |
| 41 | + fib = Fibonacci(N) |
| 42 | + print( |
| 43 | + "\n********* Enter different values to get the corresponding fibonacci sequence, enter any negative number to exit. ************\n") |
| 44 | + while True: |
| 45 | + print("Enter value: ", end=" ") |
| 46 | + i = eval(input()) |
| 47 | + if i < 0: |
| 48 | + print("\n********* Good Bye!! ************\n") |
| 49 | + break |
| 50 | + fib.get(i) |
| 51 | + except NameError: |
| 52 | + print("\nInvalid input, please try again.") |
| 53 | + except NameError: |
| 54 | + print("\n********* Invalid input, good bye!! ************\n") |
0 commit comments