Recursion | Sololearn: Learn to code for FREE!

0

Recursion

can anyone gives a perfect example to understand how the recursion works? except the factorial example.

3/13/2019 9:33:55 AM

Vinay Khatri

5 Answers

New Answer

+5

A classic recursion example second to factorial is Fibonacci sequence. Mathematically, F(n) = F(n-1) + F(n-2) with initial condition F(1) = F(2) = 1 In a Python recursive function, there are only two parts: (i) checking if the initial condition is reached. if argument is 1 or 2, return 1. (ii) calling the function itself in return, with decremenTed argument. return fibo(i-1)+fibo(i-2) Note that recursive approach builds up the stack and is subject to a stack limit based on the compiler.

+4

//Here this article covers python recursion with some demos https://www.programiz.com/python-programming/recursion

+2

Recursion is simply a function calling itself. Lets assume that i want to get the power of a number eg 2**2 using the following function. def power(x,n): if n==0: return 1 return x*power(x,n-1) >>>power(2,3) >>>8 When i call power,the values 2,3 are passed to the function. Then 2 is multiplied by 'power(x,n-1)',at this point a new identical namespace with different values is created,till calls itself continuously till n=0. It goes something like this: 1st call: 2*power(2,2) 2nd call:4*power(2,1) 3rd call:8*power(2,0) And finally you get 8.

+1

Check this out https://code.sololearn.com/cbyn6q5pRYGm/?ref=app

0

If you want to find answer to your question you need search it in the internet, as all programmers must do it. The best example to understand recursion is factorial. Look on the formula and you all understand