180 likes | 307 Views
More Recursion. Intro to Computer Science CS1510 Dr. Sarah Diesburg. Recursion – one way. A class of methods exhibit recursive behavior when they can be defined by two properties: A simple base case (or cases), and
E N D
More Recursion Intro to Computer Science CS1510 Dr. Sarah Diesburg
Recursion – one way • A class of methods exhibit recursive behavior when they can be defined by two properties: • A simple base case (or cases), and • A set of rules which reduce all other cases toward the base case. (recursive step)
Recursion – another way • A recursive function is: • One that calls itself • With “smaller” inputs (a recursive step) • Until those inputs reach a base case
A language based example… • The following is a recursive definition of a person's ancestors: • Your parents are your ancestors (base case). • The parents of your ancestors are also your ancestors (recursion step).
Recursion Humor • Recursion • See "Recursion".
Better Recursion Humor • Recursion • If you still don't get it, see "Recursion".
Some Examples of things that can be done recursively • Summation of numbers – sum(lower,upper) • Exponents - power(base,exp) • Reverse a string – reverse(string) • Merge Sort – mergeSort(lyst)
The Stack • A Stack is a data structure, like a List or a Dictionary, but with a few different characteristics. • A Stack is a sequence. • A Stack only allows access to one end of its data, the topof the stack.
Operations • pop: remove top of stack. Stack is one element smaller. • push (val): add val to the stack. Val is now the top. Stack is one element larger. • top: Reveals the top of the stack. No modification to stack.
Stack of Function Calls Python maintains a stack of function calls. • If a function calls another function recursively, the new function is pushed onto the calling stack and the previous function waits. • The top is always the active function. • When a pop occurs, the function below becomes active.
Example: Fibonacci Sequence • Start with two numbers in the sequence of 1 1 • To get the next number in the sequence, add the previous two numbers together • 1+1=2 1 1 2 • 1+2=3 1 1 2 3
How to make Fibonacci a Recursive Function • Depends on the Fibo results for the two previous values in the sequence. • The base values are Fibo(0) == 1 and Fibo(1) == 1. fibo (x) = fibo(x-1) + fibo(x-2)
Code Listing 16-3 def fibo(n): """Recursive Fibonacci sequence.""" if n == 0 or n == 1: # base case return 1 else: # divide and conquer return fibonacci(n-1) + fibonacci(n-2)
Trace • fibo(4) = fibo(3) + fibo(2) • fibo(3) = fibo(2) + fibo(1) • fibo(2) = fibo(1) + fibo(0) = 2 # base case • fibo(3) = 2 + fibo(1) = 3 # base case • fibo(4) = 3 + 2 = 5