1 Survey of Computer Science CSCI 110, Spring 2011 Lecture 14 Recursion.
Transcript of 1 Survey of Computer Science CSCI 110, Spring 2011 Lecture 14 Recursion.
1
Survey of Computer Science
CSCI 110, Spring 2011Lecture 14
Recursion
2
Recall Divide and Conquer
Draw City
Draw Building
DrawStreets
Draw Park
Draw Outline
Draw Doors
Draw Windows
Repeat Buildings
3
Recursion
Count 10000 votes
Count 5000 votes Count 5000 votes
Count 2500 votes Count 2500 votes Count 2500 votes Count 2500 votes
When the subproblems are smaller versions of the original problem, we can use recursion to solve the problem.
4
Example Draw stars
How to draw n stars using recursion:
1) Draw 1 star2) Draw (n - 1) stars
The first step is trivial, and we can simply write a line of code to do it.
The second step is a smaller version of the original problem.A function that can draw n stars can also draw n-1 stars.
5
Diagramming drawStars
Draw n stars
Draw 1 star Draw n-1 stars
Draw 1 star Draw n-2 stars
. . .
Draw 0 stars
6
DrawStars in Python
#program drawing.pyimport sys
def drawStars( n ):if n < = 0:
sys.stdout.write("")#do nothing
else:sys.stdout.write("*")drawStars( n - 1)
#Begin main program heredrawStars(2)
Base Case
General Case
7
Execution of drawStars
dS(2)
n
if n <=0:...
else: sys.stdout.write("*") drawStars(n-1)
n
if n <=0:...
else: sys.stdout.write("*") drawStars(n-1)
n
if n <=0: sys.stdout.write("") #do nothingelse:
...
8
Recursive function calls
• A recursive call is a function call in which the called function is the same as the one making the call.
• In other words, recursion occurs when a function calls itself!
• But we need to avoid making an infinite sequence of function calls (infinite recursion).
9
Finding a recursive solution
• A recursive solution to a problem must be written carefully.
• The idea is for each successive recursive call to bring you one step closer to a situation in which the problem can easily be solved.
• This easily solved situation is called the base case.
• Each recursive algorithm must have at least one base case, as well as the general case.
10
General form for recursion
if some easily-solved condition: # base case solution statement(s)
else: # general case recursive function call
11
Example: Factorial
Definition of Factorial
n! = 1 * 2 * 3 * 4 * . . . * (n-1) * n; 0! = 1
In other words:
fact(n) = 1, n = 0 n * fact( n-1), n > 0
fact( n - 1)
{
12
Writing Factorial in Python
def factorial (n):#we will write this code in class.
13
Execution of factorial
fact(2)
n
if n <= 0: return 1else: return n * fact(n - 1)
n
if n <= 0: return 1else: return n * fact(n - 1)
n
if n <= 0: return 1else: return n * fact(n - 1)
14
Invocation tree for factorial
Fact( 3) :
Fact( 2) :
Fact( 1) :
Fact( 0) :
Trace of Factorial (we will do in class)n Fact(n - 1) Fact( n )
15
Rabbit populations: Fibonacci
Months 1 2 3 4 5# pairs 1 1 2 3 5
n, n < 2fib(n-1) + fib(n-2), n <= 2{fib(n) =
16
Fibonacci in Python
def fib (n):#we will write this code in class.
17
Fibonacci Execution tree
fib (4) : 3
fib (3) : 2 fib (2) : 1
fib (2) : 1 fib (1) : 1
fib (1) : 1 fib (0) : 0
fib (1) : 1 fib (0) : 0
18
How long will this take?
For large numbers, each time you increment by 1, it takes about twice as long to compute the Fibonacci result:
Fib(32)
Fib(31) Fib(30)
Suppose our computer can process 109 operations per second.How long will it take to compute Fib(100)?(Approximate answer will be given in class).
19
Classes and Objects
Python is an object oriented programming language.All items of data are objects.
Objects have properties: Things that describe the objectsObjects have methods: Things an object can do.
A class describes a group of objects that have the same methods and set of properties.
Example: A car classProperties: color, number of doors, body typeMethods: accelerate, brake, steer
My car is an object that is a member of the car class.
20
Using Pre-defined classesPython has many libraries with pre-defined classes that we can use in our programs.
Example:The Turtle( ) class.
A turtle in python is an object from the Turtle class.
Properties: x position, y position, direction, pen position, etc.Methods: forward(distance), backward(distance), left(angle), etc.
yertle = Turtle( ) #Create a turtle object, identified as yertleyertle.forward(150) #Call the forward( ) method for yertle.
21
Writing a Class definition
class Critter: color = "red" #color is a property mood = "happy" #mood is another property def talk(self): #talk is a method print "I am a critter!" def sing(self): #sing is another method print "Tra la la"
#main program starts herecrit = Critter( )print crit.colorcrit.talk( )crit.sing( )
22
Using self in a class method
class Critter: color = "red" mood = "happy" def talk(self): print "I am a " + self.mood + " critter!"
crit = Critter( )crit.talk( )
We can use self to refer to a given object in a class method.Example:
23
The docstring
The docstring is used to describe the objects in a class.
Example:
class Critter: """A virtual pet"""
...
crit = Critter( ):print crit.__doc__
24
The constructor functionWe can use a constructor function to initialize properties.
Example:class Critter: """A virtual pet""" def __init__(self, clr, md): self.color = clr self.mood = md def talk(self): print "I am a " + self.mood + " critter!"
crit = Critter("green", "sad")print crit.colorcrit.talk( )