#Memoziation Fibonacci fibtable={} def fib(n): if n in fibtable: #As sir said, you can use dictionary to check return(fibtable[n]) if n==0 or n==1: value=n else: value=fib(n-1)+fib(n-2) fibtable[n]=value return(value) #Dynamic Fibonacci def fibonacci(n): fibtable=[0,1] for i in range(2,n+1): fibtable.append(fibtable[i-1]+fibtable[i-2]) return(fibtable[n]) print(fib(15)) print(fibonacci(15))
@shreemannarayan57554 жыл бұрын
def fibonacci(n): fibtable=[None]*n fibtable[0]=1 fibtable[1]=1 for i in range(2,n): fibtable[i]=fibtable[i-1]+fibtable[i-2] return fibtable print(fibonacci(50))
@ytg66633 жыл бұрын
It is wrong...LoL
@ytg66633 жыл бұрын
Nice
@yesfortravel075 жыл бұрын
Hi sir, def fab(n): fibtable[0]=0 fibtable[1]=1 for i in range(2,n+1): fibtable[i]=fibtable[i-1]+fibtable[i-2] return fibtable[n] fab(5) i'm not able to execute this problem it's show name error.can you please suggest?
@a_maxed_out_handle_of_30_chars5 жыл бұрын
Create a empty dictionary first with the name fibtable, then it'll work i.e write fibtable = {} as the first line INTO the function.
@debojyotisinha50315 жыл бұрын
fibtable = {} def fib(n): try: if fibtable[n]: return(fibtable[n]) except KeyError: pass if n == 0 or n == 1: fibtable[n] = n return(n) else: value = fib(n-1) + fib(n-2) fibtable[n] = value return(value)
@debojyotisinha50315 жыл бұрын
fibtable = {} def fib(n): fibtable[0] = 0 fibtable[1] = 1 for i in range(2, n+1): fibtable[i] = fibtable[i-1] + fibtable[i-2] return(fibtable[n])