You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#Recursive version which we will write mostly!deffibonacciVal(n)ifn == 0return0elsifn == 1return1elsereturnfibonacciVal(n-1) + fibonacciVal(n-2)endend#Memoized version ... Just see the difference in executiondeffibonacciValNew(n)memo=[0] * (n+1)memo[0],memo[1]=0,1foriin(2..n+1)memo[i]=memo[i-1] + memo[i-2]endreturnmemo[n]endt1=Time.nowfibonacciVal(40)puts"Time taken =====> #{(Time.now - t1) * 1000}"t2=Time.nowfibonacciValNew(40)puts"Time taken =====> #{(Time.now - t2) * 1000}"
Python version
#Memoized version ... Just see the difference in executiondeffibonacciVal(n):
ifn==0:
return0elifn==1:
return1else:
returnfibonacciVal(n-1) +fibonacciVal(n-2)
#Memoized version ... Just see the difference in executiondeffibonacciValNew(n):
memo= [0] * (n+1)
memo[0], memo[1] =0, 1foriinrange(2, n+1):
memo[i] =memo[i-1] +memo[i-2]
returnmemo[n]
t1=time.time()
fibonacciVal(40)
print((time.time() -t1) *1000)
t2=time.time()
fibonacciValNew(40)
print((time.time() -t2) *1000)
Golang version
package main
import (
"fmt""time"
)
funcmain() {
t1:=time.Now()
fmt.Println(fibonacciVal(40))
fmt.Println("Time taken ==========> ", time.Since(t1))
t2:=time.Now()
fmt.Println(fibonacciValNew(40))
fmt.Println("Time taken ==========> ", time.Since(t2))
}
// Recursive version which we will write mostly!funcfibonacciVal(nint) (int) {
ifn==0 {
return0
} elseifn==1 {
return1
} else {
return (fibonacciVal(n-1) +fibonacciVal(n-2))
}
}
// Memoized version ... Just see the difference in executionfuncfibonacciValNew(nint) (int) {
rangeArr:=make([]int, n+2)
memo:=make([]int, n+2)
fori:=1; i<n+2; i++ {
rangeArr[i] =i
}
memo[1] =1fori:=2; i<n+2; i++ {
memo[i] = (memo[i-1] +memo[i-2])
}
returnmemo[n]
}
Results
Time in ms
Ruby
Python 2.7
GoLang
Recursive Algo
25410.060878
33261.4440918
806.313542
Memoized Algo
1.715674
0.661849975586
0.007878
Ruby seems working fine in recursion, compared to python. But in datastructur-ed memoization, python works faster. And golang out performs both of them - 806 ms compared to 25.4 and 33.3 seconds!