Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 16 Online
OpenStudy (anonymous):

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

OpenStudy (lyrae):

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)

OpenStudy (anonymous):

Ok i got this. so whats the difference between the recursion function and the while loop?

OpenStudy (lyrae):

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

OpenStudy (rsmith6559):

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

OpenStudy (anonymous):

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.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!