Nov-28-2018, 08:37 AM
(Nov-24-2018, 02:49 AM)frequency Wrote:def fib(number): if number==0: return 0 elif number==1: return 1 else: return fib(number-1)+fib(number-2)With this code i can show the N fibonacci number given. But my code is not accepted because of this
***Time limit exceeded***. Any ideas?
It seems to me that you can't have Fibonacci without recursive solution (at least in school / university) :-). This is somehow considered 'appropriate' way of learning recursion. Recursion can be helpful but it's memory hungry and it's not very well suited for Python. However, if you absolutely must use recursion and the number is not very large (so that Python recursion depth is not reached) you can take advantage of memoization and fit nicely into time limit.
import time start_time = time.time() def fibonacci(n, d): """ Calculate n-th Fibonacci number using recursion with memoization. """ if n in d: return d[n] else: stacked = fibonacci(n - 1, d) + fibonacci(n-2, d) d[n] = stacked return stacked d = {1: 1, 2: 1} print(fibonacci(2967, d)) # max value print(f'time: {time.time() - start_time} seconds') 5210070734289118676556659504172397216509110684811035423298698167608113070 8128298569412879157715400318322090085906471884461561425531080766704209506 4311080110751154013406591832134966583308143574796700315698273930037147293 5213339912864755255418769562822777951268745753053628637531122736216232998 2608605087960788184953369249606869764593142447603256366652678730040462508 2678511875453604344284964368071643450341691576353630336917618689891862786 8101774706249610049853926508865933137189372424857166415874230698017498326 2019706158006070552174196824071976060605681771809636978040161730581446676 084619548504486422369069065085516578 time: 0.005608797073364258 seconds
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.