File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ # Author: OMKAR PATHAK 
2+ 
3+ # recursive fibonacci solution has a time complexity of O(2 ^ n). 
4+ # To reduce this we can use dynamic programming. Dictionary data structure is used to drastically reduce 
5+ # the time complexity to O(n) 
6+ 
7+ import  time 
8+ 
9+ # improved fibonacci function 
10+ def  fibonacci (number ):
11+     if  myList [number ] ==  None :
12+         myList [number ] =  fibonacci (number  -  1 ) +  fibonacci (number  -  2 )
13+     return  myList [number ]
14+ 
15+ # traditional recursive fibonacci function 
16+ def  fibonacciRec (number ):
17+     if  number  <=  1 :
18+         return  number 
19+     else :
20+         return  (fibonacciRec (number  -  1 ) +  fibonacciRec (number  -  2 ))
21+ 
22+ if  __name__  ==  '__main__' :
23+     userInput  =  int (input ('Enter the number: ' ))
24+ 
25+     myList  =  [None  for  _  in  range (userInput  +  1 )]
26+ 
27+     # base cases 
28+     myList [0 ] =  0 
29+     myList [1 ] =  1 
30+ 
31+     startTime  =  time .time ()
32+     result  =  fibonacci (userInput )
33+     stopTime  =  time .time ()
34+     print ('Time:' , (stopTime  -  startTime ), 'Result:' , result )
35+ 
36+     startTime  =  time .time ()
37+     result  =  fibonacciRec (userInput )
38+     stopTime  =  time .time ()
39+     print ('Time:' , (stopTime  -  startTime ), 'Result:' , result )
    
 
   
 
     
   
   
          
     
  
    
     
 
    
      
     
 
     
    You can’t perform that action at this time.
  
 
    
  
     
    
      
        
     
 
       
      
     
   
 
    
    
  
 
  
 
     
    
0 commit comments