Can someone tell me the execution of this code? | Sololearn: Learn to code for FREE!

+7

Can someone tell me the execution of this code?

https://code.sololearn.com/cZ5P5k9746t8/?ref=app

5/13/2020 6:43:16 AM

Punit Kumar

24 Answers

New Answer

+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

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))

+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

+3

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. 😎

+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

https://m.facebook.com/profile.php?id=100023288953813&tsid=0.5404534164180121&source=result