forked from OmkarPathak/Data-Structures-using-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP01_Fibonnaci.py
More file actions
39 lines (30 loc) · 1.09 KB
/
P01_Fibonnaci.py
File metadata and controls
39 lines (30 loc) · 1.09 KB
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
# Author: OMKAR PATHAK
# recursive fibonacci solution has a time complexity of O(2 ^ n).
# To reduce this we can use dynamic programming. Dictionary data structure is used to drastically reduce
# the time complexity to O(n)
import time
# improved fibonacci function
def fibonacci(number):
if myList[number] == None:
myList[number] = fibonacci(number - 1) + fibonacci(number - 2)
return myList[number]
# traditional recursive fibonacci function
def fibonacciRec(number):
if number == 1 or number == 0:
return number
else:
return (fibonacciRec(number - 1) + fibonacciRec(number - 2))
if __name__ == '__main__':
userInput = int(input('Enter the number: '))
myList = [None for _ in range(userInput + 1)]
# base cases
myList[0] = 0
myList[1] = 1
startTime = time.time()
result = fibonacci(userInput)
stopTime = time.time()
print('Time:', (stopTime - startTime), 'Result:', result)
startTime = time.time()
result = fibonacciRec(userInput)
stopTime = time.time()
print('Time:', (stopTime - startTime), 'Result:', result)