+ 7
Can someone tell me the execution of this code?
24 Respostas
+ 6
s=011235
is the series u create
s[5]=5
+ 13
def num(n):
if n==0:
return 0
if n==1:
return 1
else:
return ((num(n-1)+num(n-2)))
print (num(5))
Here,
you have called the function with int 5 so n=5
num(5-1) + num(5-2)
------------------------------
|
num(4) + num(3)
| |
num(3) + num(2)+num(2) + num(1)
| | | |
num(2)+num(1) | num(1)+num(0) |
| | | | | |
1+0 + 1 + 1+0 + 1 + 0 + 1
if n==1: return 1
if n==0: return 0
1+0+1+1+0+1+0+1 = 5
+ 9
Code Crasher
pencil and paper will do.
you are experienced enough to get a foot into recursion.
give it a try... it is fascinating
+ 8
Punit Kumar
yes it is and it takes a while.
but it us worth it.
Do you agree?
+ 7
This is Fibonacci series.. A pain in the *** , sorry but it's really difficult. It's often set as an example when teaching recursion.
The iterative alternative of your code is :
first,second = 0,1
for i in range(n): # e.g.: n=5
first, second = second, first+second
print(first)
+ 4
5
+ 3
Pen and paper worked fine for me later but it's quite complicated mentally...But you method is lit Oma Falk
+ 3
Oma Falk Totally agreed 👍
+ 3
PEN and PAPER will do the trick!
It's simple recursion...
+ 3
Pranav Shinde
pencil and paper😉
+ 3
It is fibonachi series 01123581321 so each number in set is a sum of 2 previous( first in set is 0 second is 1)
+ 3
According to your code you will get the output as 5
+ 3
It is a fibonacci series.
+ 3
It is a recursive function which can call itself. In this situration you call it with the parameter 5 which is "n". n is not 0 or 1, so the function call itself again with the new parameters until n is 0 or 1. Be careful that the very first function called is the last one which comoletes. Just draw a dragram as Lay_in_life says.
+ 2
Take a pen and paper and start writing in order of execution
+ 2
IT's 5
+ 2
num(5)
↓
num(4)+num(3)→num(2)+num(1)
↓ .
num(3)+num(2)
↓
num(2)+num(1)→1
↓
num(1)+num(0)
↓ ↓
1 0
num(2)=1
num(3)=num(2)+num(1)=1+1=2
num(4)=num(3)+num(2)=2+1=3
num(5)=num(4)+num(3)=3+2=5
+ 1
5, guys above explained you why and i had a lot of fun doing it. You should try yourself also:)
+ 1
Answer is 5 bro.
num[5]=num[4]+num[3]
=num[3]+num[2]+num[2]+num[1]
And here given for num[1]=1 and num[0]=0 so,
=num[2]+num[1]+num[1]+num[0]+num[1]+num[0]+1
=num[1]+num[0]+1+1+0+1+0+1
=1+0+1+1+0+1+0+1
=5