Download presentation
Presentation is loading. Please wait.
Published byShannon Carter Modified over 6 years ago
1
Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
More Recursion Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg
2
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)
3
Recursion – another way
A recursive function is: One that calls itself With “smaller” inputs (a recursive step) Until those inputs reach a base case
4
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).
5
Recursion Humor Recursion See "Recursion".
6
Better Recursion Humor
If you still don't get it, see "Recursion".
7
Recursion Humor
8
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)
9
How Does the Computer Keep Track?
10
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 top of the stack.
12
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.
14
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.
15
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
16
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)
17
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)
18
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) = = 5
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.