24 Answers
New Answerhttps://code.sololearn.com/cZ5P5k9746t8/?ref=app
5/13/2020 6:43:16 AM
Punit Kumar24 Answers
New Answerdef 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
Code Crasher pencil and paper will do. you are experienced enough to get a foot into recursion. give it a try... it is fascinating
Oma Falk Always pencil & paper not works πππ If anyone has doubt how 011235 has created try this simple code def num(n): if n==0: return 0 if n==1: return 1 else: return ((num(n-1)+num(n-2))) for i in range(6): print (num(i))
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)
Punit Kumar That is some serious recursion that somehow works?! I think I may have to step that one thru a debugger to see what it is doing. Thanks for sharing. π Oma Falk Thanks for the explanation I dont think I would have had a clue otherwise. Now I at least know what to look for. π
Pen and paper worked fine for me later but it's quite complicated mentally...But you method is lit Oma Falk
It is fibonachi series 01123581321 so each number in set is a sum of 2 previous( first in set is 0 second is 1)
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.
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
https://m.facebook.com/profile.php?id=100023288953813&tsid=0.5404534164180121&source=result
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message