Please i'm finding it difficult to grasp how recursion is being implemented in python. Can anyone walk me through on Recursion function. Maybe with a simple example. Thanks
A function with recursion is simply a function calling it self one or several times. Here's a classic example using recursion to calculate the nth factorial: def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1)
Ok i got this. so whats the difference between the recursion function and the while loop?
Like I wrote, a recursive function is a functiong calling it self. They usually have some condition to fill for the recursion to stop (n==0 in the case with the factorial function) and some value it modifies and passes as argument to reach that condition (factorial(n - 1) in the factorial case). A while loop is a statement you (usually) find INSIDE a function and is used to repeat some pice of code untill a certain condition is meet. Example python while loop: print "1-9" count = 1 while (count <= 9): print 'count: ', count count = count + 1
A recursive function solves part of a problem on each recursion. A recursive function has to satisfy three things: how to recurse more, when to stop recursing (this is called the base case) and what to do as it "unwinds" (all those recursions returning). Reversing a string is a simple recursive task: def reverse( string ): if( len( string ) == 0 ): # the base case return "" else: char = string[ 0 ] # recurse more, and on the unwind # concatenate the string return( reverse( string[ 1: ] ) + char ) if( __name__ == "__main__" ): print reverse( "Hello World" )
I typically use factorials as a quick example of a problem to be solved recursively. A factorial of a number is the product of all integers less than or equal to that number. For example, 3! would be equal to 3x2x1=6, and 4! would be 4x3x2x1=24 etc. All you're really looking for in the answer is the factorial, but you have to do the same operation n number of times to actually arrive at that result. You could definitely do it with a loop, but a recursive solution is usually a bit more elegant based on code length.
Join our real-time social learning platform and learn together with your friends!