0% found this document useful (0 votes)
16 views35 pages

Recursion: Python Programming, 3/e 1

COMPUTER PROGRAMMING BASICS

Uploaded by

Kritansh Uppal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views35 pages

Recursion: Python Programming, 3/e 1

COMPUTER PROGRAMMING BASICS

Uploaded by

Kritansh Uppal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Recursion

Python Programming, 3/e 1


Recursive Definitions
n A description of something that refers
to itself is called a recursive definition.

Python Programming, 3/e 2


Recursive Definitions
n In mathematics, recursion is frequently
used. The most common example is the
factorial:
n For example, 5! = 5(4)(3)(2)(1), or
5! = 5(4!)
n! = n(n - 1)(n - 2)...(1)

Python Programming, 3/e 3


Recursive Definitions
n In other words, n! = n(n - 1)!

Or n ! = ì 1 if n = 0
n
í
în(n - 1)! otherwise
n This definition says that 0! is 1, while
the factorial of any other number is that
number times the factorial of one less
than that number.

Python Programming, 3/e 4


Recursive Definitions
n Our definition is recursive
n Consider 4!
n 4! = 4(4-1)! = 4(3!)
n What is 3!? We apply the definition again
4! = 4(3!) = 4[3(3-1)!] = 4(3)(2!)
n And so on…
4! = 4(3!) = 4(3)(2!) = 4(3)(2)(1!) =
4(3)(2)(1)(0!) = 4(3)(2)(1)(1) = 24

Python Programming, 3/e 5


Recursive Definitions
n we eventually get to 0!, whose
definition does not rely on the definition
of factorial and is just 1. This is called a
base case for the recursion.
n When the base case is encountered, we
get a closed expression that can be
directly computed.

Python Programming, 3/e 6


Recursive Definitions
n All good recursive definitions have these two
key characteristics:
n There are one or more base cases for which no
recursion is applied.
n All chains of recursion eventually end up at one of
the base cases.

Python Programming, 3/e 7


Recursive Functions

n If factorial is written as a separate


function:
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)

Python Programming, 3/e 8


Recursive Functions
n We’ve written a function that calls itself,
a recursive function.
n The function first checks to see if we’re
at the base case (n==0). If so, return 1.
Otherwise, return the result of
multiplying n by the factorial of n-1,
fact(n-1).

Python Programming, 3/e 9


Recursive Functions
>>> fact(4)
24
>>> fact(10)
3628800
>>> fact(100)
9332621544394415268169923885626670049071596826438162146
85929638952175999932299156089414639761565182862536979
20827223758251185210916864000000000000000000000000L
>>>

n Remember that each call to a function


starts that function anew, with its own
copies of local variables and
parameters.
Python Programming, 3/e 10
Recursive Functions

Python Programming, 3/e 11


Example: String Reversal
n Python lists have a built-in method that
can be used to reverse the list. What if
you wanted to reverse a string?
n If you wanted to program this yourself,
one way to do it would be to convert
the string into a list of characters,
reverse the list, and then convert it
back into a string.
Python Programming, 3/e 12
Example: String Reversal
n Using recursion, we can calculate the
reverse of a string without the
intermediate list step.
n Think of a string as a recursive object:
n Divide it up into a first character and “all
the rest”
n Reverse the “rest” and append the first
character to the end of it
Python Programming, 3/e 13
Example: String Reversal
n def reverse(s):
return reverse(s[1:]) + s[0]

n The slice s[1:] returns all but the first


character of the string.
n We reverse this slice and then
concatenate the first character (s[0])
onto the end.

Python Programming, 3/e 14


Example: String Reversal
>>> reverse("Hello")
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
reverse("Hello")
File "<pyshell#2>", line 2, in reverse
return reverse(s[1:]) + s[0]
File "<pyshell#2>", line 2, in reverse
return reverse(s[1:]) + s[0]

File "<pyshell#2>", line 2, in reverse
return reverse(s[1:]) + s[0]
RecursionError: maximum recursion depth exceeded

n What happened? There were 1000 lines


of errors!

Python Programming, 3/e 15


Example: String Reversal
n Remember: To build a correct recursive
function, we need a base case that
doesn’t use recursion.
n We forgot to include a base case, so
our program is an infinite recursion.
Each call to reverse contains another
call to reverse, so none of them
return.
Python Programming, 3/e 16
Example: String Reversal
n Each time a function is called it takes some
memory. Python stops it at 1000 calls, the
default “maximum recursion depth.”
n What should we use for our base case?
n Following our algorithm, we know we will
eventually try to reverse the empty string.
Since the empty string is its own reverse, we
can use it as the base case.

Python Programming, 3/e 17


Example: String Reversal
n def reverse(s):
if s == "":
return s
else:
return reverse(s[1:]) + s[0]
n >>> reverse("Hello")
'olleH'

Python Programming, 3/e 18


Example: Anagrams
n An anagram is formed by rearranging
the letters of a word.
n Anagram formation is a special case of
generating all permutations
(rearrangements) of a sequence, a
problem that is seen frequently in
mathematics and computer science.

Python Programming, 3/e 19


Example: Anagrams
n Let’s apply the same approach from the
previous example.
n Slice the first character off the string.
n Place the first character in all possible
locations within the anagrams formed from
the “rest” of the original string.

Python Programming, 3/e 20


Example: Anagrams
n Suppose the original string is “abc”. Stripping
off the “a” leaves us with “bc”.
n Generating all anagrams of “bc” gives us “bc”
and “cb”.
n To form the anagram of the original string,
we place “a” in all possible locations within
these two smaller anagrams: [“abc”, “bac”,
“bca”, “acb”, “cab”, “cba”]

Python Programming, 3/e 21


Example: Anagrams
n As in the previous example, we can use
the empty string as our base case.
n def anagrams(s):
if s == "":
return [s]
else:
ans = []
for w in anagrams(s[1:]):
for pos in range(len(w)+1):
ans.append(w[:pos]+s[0]+w[pos:])
return ans

Python Programming, 3/e 22


Example: Anagrams
n A list is used to accumulate results.
n The outer for loop iterates through each
anagram of the tail of s.
n The inner loop goes through each position in
the anagram and creates a new string with
the original first character inserted into that
position.
n The inner loop goes up to len(w)+1 so the
new character can be added at the end of the
anagram.

Python Programming, 3/e 23


Example: Anagrams
n w[:pos]+s[0]+w[pos:]
n w[:pos] gives the part of w up to, but not
including, pos.
n w[pos:] gives everything from pos to
the end.
n Inserting s[0] between them effectively
inserts it into w at pos.

Python Programming, 3/e 24


Example: Anagrams
n The number of anagrams of a word is
the factorial of the length of the word.
n >>> anagrams("abc")
['abc', 'bac', 'bca', 'acb', 'cab', 'cba']

Python Programming, 3/e 25


Recursion vs. Iteration
n There are similarities between iteration
(looping) and recursion.
n In fact, anything that can be done with a loop
can be done with a simple recursive function!
Some programming languages use recursion
exclusively.
n Some problems that are simple to solve with
recursion are quite difficult to solve with
loops.
Python Programming, 3/e 26
Recursion vs. Iteration
n So… will recursive solutions always be
as efficient or more efficient than their
iterative counterpart?
n The Fibonacci sequence is the sequence
of numbers 1,1,2,3,5,8,…
n The sequence starts with two 1’s
n Successive numbers are calculated by
finding the sum of the previous two
Python Programming, 3/e 27
Recursion vs. Iteration
n Loop version:
n Let’s use two variables, curr and prev, to
calculate the next number in the sequence.
n Once this is done, we set prev equal to
curr, and set curr equal to the just-
calculated number.
n All we need to do is to put this into a loop
to execute the right number of times!

Python Programming, 3/e 28


Recursion vs. Iteration
n def loopfib(n):
# returns the nth Fibonacci number

curr = 1
prev = 1
for i in range(n-2):
curr, prev = curr+prev, curr
return curr
n Note the use of simultaneous assignment to
calculate the new values of curr and prev.
n The loop executes only n-2 times since the
first two values have already been
“determined”.
Python Programming, 3/e 29
Recursion vs. Iteration
n The Fibonacci sequence also has a recursive
definition:
ì 1 if n < 3
fib(n) = í
î fib(n - 1) + fib(n - 2) otherwise
n This recursive definition can be directly
turned into a recursive function!
n def fib(n):
if n < 3:
return 1
else:
return fib(n-1)+fib(n-2)

Python Programming, 3/e 30


Recursion vs. Iteration
n This function obeys the rules that we’ve
set out.
n The recursion is always based on smaller
values.
n There is a non-recursive base case.
n So, this function will work great, won’t
it? – Sort of…

Python Programming, 3/e 31


Recursion vs. Iteration
n The recursive solution is extremely
inefficient, since it performs many
duplicate calculations!

Python Programming, 3/e 32


Recursion vs. Iteration

n To calculate fib(6), fib(4)is calculated twice,


fib(3)is calculated three times, fib(2)is
calculated four times… For large numbers, this
adds up!
Python Programming, 3/e 33
Recursion vs. Iteration
n Recursion is another tool in your problem-
solving toolbox.
n Sometimes recursion provides a good solution
because it is more elegant or efficient than a
looping version.
n At other times, when both algorithms are
quite similar, the edge goes to the looping
solution on the basis of speed.
n Avoid the recursive solution if it is terribly
inefficient, unless you can’t come up with an
iterative solution (which sometimes happens!)
Python Programming, 3/e 34
7696543324
n Thank you

Python Programming, 3/e 35

You might also like