import time def fibo(n): if (n == 1 or n == 2): return(1) else: return(fibo(n-1)+fibo(n-2)) def fibo2(n): prev = 1 curr = 1 if (n == 1 or n == 2): return(1) elif (n < 1): return(-1) else: hasil = curr + prev for i in range(2, n): hasil = curr + prev prev = curr curr = hasil return(hasil) iterasi = 40 start = time.time() for i in range(iterasi): fibo(i+1) end = time.time() print("recursive " + str(end - start)) start = time.time() for i in range(iterasi): fibo2(i+1) end = time.time() print("for " + str(end - start))Output on my machine:
Monday, April 1, 2019
Python example recursive
The fibo function is using recursive. The fibo2 function using looping. Both of them will generate a Fibonacci sequence. Using recursive make our code shorter, but how about the performance?
Subscribe to:
Posts (Atom)