90 likes | 164 Views
Object-oriented programming CSI32. Dr. Sharon Persinger October 30, 2013. Recursion. Recursion is a type of repetition used in mathematics and computing to create objects and to define functions.
E N D
Object-oriented programmingCSI32 Dr. Sharon Persinger October 30, 2013
Recursion • Recursion is a type of repetition used in mathematics and computing to create objects and to define functions. • The key to recursion is to see that some objects or functions have smaller instances of the same object or function inside them.
Functional recursion • Functional recursion allows you to define a function in terms of itself. (What?) • A recursive definition for a function F includes a call of the function F in the function definition for F.
Example: Factorial function F • F(n)= n(n-1)(n-2)…3⋅2⋅1, for integer n ≥0 • F(0) = 1 • Can you see a factorial on the right hand side of the definition?
Example: Factorial function F • Base case: F(0) = 1; F(1) = 1 • Recursive case: for n ≥2, F(n) = n ⋅F(n-1) • Trace the evaluation of F(4). • In Python, an activation record keeps track of information relevant to a function call – parameter values, interruptions. • Write a recursive definition in Python for the factorial function
Programming Assignment • Write a recursive definition for the factorial function. Now!
Recursive GCD function using Euclid’s algorithm • Remember Euclid’s Algorithm from CSI30? • Key idea: GCD(A, B) = GCD(B, A mod B) • Do example GCD(300, 45) • When do you know the GCD? • What is the base case? • What does the recursive call look like?
Recursive GCD function • Write a recursive definition for GCD using Euclid’s algorithm – Now!
Recursive function definition for G • There must be one or more base cases that can be evaluated without calling G • There must be one or more cases where G is evaluated by calling G on a simpler or smaller input – recursive call. • Every recursive call must end in a base case.