Q.
1
) Run each of the following codes in your favorite program. All lines to report the execution time. Which algorithm is fastest?
Iterative Approach
1
2 3 4 5 6 7 8 9 10 11 12 |
def fib_iter(n): a=1 b=1 if n==1: print(‘0’) elif n==2: print(‘0′,’1’) else: print(“Iterative Approach: “, end=’ ‘) print(‘0′,a,b,end=’ ‘) for i in range(n-3): total = a + b b=a a= total print(total,end=’ ‘) print() return b fib_iter(5) |
TEST THE CODE (Links to an external site.)
Output : Iterative Approach : 0 1 1 2 3
Recursive Approach
def fib_rec(n): if n == 1: return [0] elif n == 2: return [0,1] else: x = fib_rec(n-1) # the new element the sum of the last two elements x.append(sum(x[:-3:-1])) return x x=fib_rec(5) print(x) |
TEST THE CODE (Links to an external site.)
Output – 0, 1, 1, 2, 3
Dynamic Programming Approach
12345678910111
21 3141516171819 20 21 22 |
There is a slight modification to the iterative approach. We use an additional array. def fib_dp(num): arr = [0,1] print(“Dynamic Programming Approach: “,end= ‘ ‘) if num==1: print(‘0’) elif num==2: print(‘[0,’,’1]’) else: while(len(arr) arr.append(0) if(num==0 or num==1): return 1 else: arr[0]=0 arr[1]=1 for i in range(2,num): arr[i]=arr[i-1]+arr[i-2] print(arr) return arr[num-2] fib_dp(5) |
TEST THE CODE (Links to an external site.)Output – 0, 1, 1, 2, 3
If you found this blog helpful,
learn artificial intelligence (Links to an external site.)
and power ahead in your career. Learn from the best in the industry and also gain access to mentorship sessions and career assistance.
From <
https://www.mygreatlearning.com/blog/fibonacci-series-in-python/#fibonacciDynamic (Links to an external site.)
>