0% found this document useful (0 votes)
6 views

Introduction To Programming in Python

Uploaded by

itsabhi027
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Introduction To Programming in Python

Uploaded by

itsabhi027
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Factorial Function

Consider the factorial function:


Introduction to Programming in Python
k! = 1 ∗ 2 ∗ . . . ∗ (k − 1) ∗ k.
Recursion

This is often defined mathematically by the following recurrence


Abhishek Kumar Singh relation:
Department of Computer Science
1! = 1
n! = n ∗ (n − 1)!, for n > 1

It is typically quite easy to implement a function in Python directly


from the recurrence relation.

Factorial Function Factorial Function

1! = 1
n! = n ∗ (n − 1)!, for n > 1 Mathematical definition:

1! = 1
n! = n ∗ (n − 1)!, for n > 1
For example, to compute 5! we do the following:
5! = 5 ∗ 4! (1)
Here’s a straightforward implementation in Python.
= 5 ∗ (4 ∗ 3!) (2)
def fact ( n ) :
= 5 ∗ (4 ∗ (3 ∗ 2!)) (3) """ Factorial function . """
if n == 1: # base case
= 5 ∗ (4 ∗ (3 ∗ (2 ∗ 1!))) (4) return 1
= 5 ∗ (4 ∗ (3 ∗ (2 ∗ 1))) (5) else :
return n * fact (n -1) # recursive case
= 5 ∗ (4 ∗ (3 ∗ 2)) (6)
= 5 ∗ (4 ∗ 6) (7) This function is recursive because it calls itself.
= 5 ∗ 24 (8) Can you see anything wrong with this? How might you fix it?
= 120 (9)
How to Think about Recursion Factorial Again

Whenever you’re trying to think about a recursive problem, take


1! = 1
the following three steps:
n! = n ∗ (n − 1)!, for n > 1
1 Think of the simplest instances of the problem, ones that can
be solved directly.
2 For more complex instances, assume you can solve an instance 1 The simplest case (base case) is n = 1.
that is one step simpler. 2 The more complex case is n!. Assume you know how to solve
3 Think how you’d get from a solution of that simpler problem a case that is one step simpler, (n − 1)!.
to a solution to your more complex problem. 3 If you could do that, you’d solve n! by multiplying n ∗ (n − 1)!.

Another Example Running Our Code

How would you define a recursive function listSum(lst) to add


together all the elements of a list of numbers.
1 In the simplest (base) case, lst is empty. Then
listSum(lst) is 0. >>> from recursionExamples import *
2 Now suppose lst isn’t empty, i.e., it’s [x, y,...,z], and >>> listSum ([])
assume we knew how to find listSum([y,...,z]). 0
3 Then we solve our problem by adding x to >>> listSum ([1 , 3 , 5 , 8 , -10])
listSum([y,...,z]). 7

def listSum ( lst ) :


if lst == []:
return 0
else :
return lst [0] + listSum ( lst [1:] )
Three Laws of Recursion Some Faulty Examples

def factBad ( n ) :
1 A recursive function must have one or more base return n * factBad ( n - 1 )
cases—calculated directly without a recursive call.
2 It must have one or more recursive calls; without that it’s not def isEven ( n ) :
recursive. if n == 0:
3 Each recursive call must move the computation closer to a return True
base case (usually by making the argument “smaller” in the else :
recursive call). return isEven ( n - 2)

What’s wrong and how would you fix these?

Recursive Thinking: Some Examples Recursive Thinking: Some Examples


Example: how can you count the occurrences of key in list L?
Example: how many items are in a list L?
Base case: If L is empty, the count is 0.
Base case: If L is empty, length is 0. Recursive case: If L starts with key, then it’s 1 plus the count in
Recursive case: If I knew the length of L[1:], then I could compute the rest of the list; otherwise, it’s just the count in
the length of L. How? the rest of the list.
def c o u n t O c c u r r e n c e s I n L i s t ( key , L ) :
def co unt ItemsI nL ist ( L ) :
""" Recursively count the occurrences of key in L . """
""" Recursively count the number of items in list . """
if L == []:
if L == []: # not L : also works . Why ?
return 0
return 0
elif key == L [0]:
else :
return 1 + c o u n t O c c u r r e n c e s I n L i s t ( key , L [1:] )
return 1 + cou n tI te m sI n Li st ( L [1:] )
else :
return c o u n t O c c u r r e n c e s I n L i s t ( key , L [1:] )
>>> l1 = [ 1 , 2 , 3 , " red " , 2.9 ]
>>> c ou ntItem sInList ( l1 ) >>> lst = [ 5 , 6 , 14 , -3 , 0 , -70 , 6 ]
5 >>> c o u n t O c c u r r e n c e s I n L i s t ( 3 , lst )
0
Does this work for any list? >>> c o u n t O c c u r r e n c e s I n L i s t ( 6 , lst )
2

Texas Summer Discovery Slideset 12: 11 Recursion Texas Summer Discovery Slideset 12: 12 Recursion
Recursive Thinking: Some Examples Recursive Thinking: Some Examples
An algorithm that dates from Euclid finds the greatest common
Example: how can you reverse a list L? divisor of two positive integers:

Base case: If L is empty, the reverse is []. gcd(a, b) = a, if a = b


gcd(a, b) = gcd(a − b, b), if a > b
Recursive case: If L is not empty, remove the first element and
gcd(a, b) = gcd(a, b − a), if b > a
append it to end of the reverse of the rest.
def gcd ( a , b ) :
def reverseList ( L ) : """ Euclid ’s algorithm for GCD . """
""" Recursively reverse a list . """ print ( " Computing gcd ( " , a , " ," , b , " ) " )
if L == []: if a < b :
return [] return gcd ( a , b - a )
else : elif b < a :
return reverseList ( L [1:] ) + [ L [0] ] return gcd ( a -b , b )
else :
print ( " Found gcd : " , a )
>>> lst = [ 1 , 5 , " red " , 2.3 , 17 ]
return a
>>> print ( reverseList ( lst ) )
[17 , 2.3 , ’ red ’ , 5 , 1]
print ( " gcd ( 68 , 119 ) = " , gcd ( 68 , 119 ) )

What is assumed about a and b? What is the base case? The


recursive cases?

Running GCD Some Exercises for You to Try

1 Write a recursive function to append two lists.


2 Write a recursive version of linear search in a list.
> python gcd . py
Computing gcd ( 68 , 119 )
3 Write a recursive function to sum the digits in a decimal
Computing gcd ( 68 , 51 ) number.
Computing gcd ( 17 , 51 ) 4 Write a recursive function to check whether a string is a
Computing gcd ( 17 , 34 ) palindrome.
Computing gcd ( 17 , 17 )
gcd ( 68 , 119 ) = 17 It’s probably occurred to you that many of these problems were
already solved with built in Python methods or could be solved
with loops.
That’s true, but our goal is to teach you to think recursively!

You might also like