Docsity

Recursion - Introduction to Computing Using Python - Lecture Slides, Slides of Introduction to Computing

Partial preview of the text

Download Recursion - Introduction to Computing Using Python - Lecture Slides and more Slides Introduction to Computing in PDF only on Docsity!

Reminder: our running example

def num_es(s):

"""Returns: number of ‘e’s in . Precond: a string"""

# Strategy: break off first character, recur on the rest.

if s == '': # base case (no recursion): is empty string

return 0

# recursive case: process 1

st

char and rest of string

# note: s[1:] is '' if len(s) <= 1

return ((1 if s[0] == 'e' else 0) + num_es(s[1:]))

Let's understand what happens at execution.

1 2 3

import lec print lec12.num_es('ae') code with function call s num_es:1 3 'e' s num_es:1 3 'ae'

Execution in "typical" recursion case

def num_es(s): if s == '': return 0 return ((1 if s[0] == 'e' else 0) + num_es(s[1:])) 1 2 3 inside module lec 12 import creates the function objects that are defined in lec12, like num_es, so we can call them. s num_es:1 2 '' ✗ ✗ ✗ ✗

print oops('ae') code with function call

What if we didn't have a base case (version I)?

def oops(s): 1 return ((1 if s[0] == 'e' else 0)^ +^ oops (s[1:])) hypothetical function definition s oops: 1 'ae' s oops: 1 'e' s oops: 1 '' ... error (index error) when splitting not applicable

print oops('ae') code with function call

What if we didn't have a base case (version II)?

def oops(s): 1 return ((1 if^ s[0:1]^ == 'e' else 0)^ +^ oops (s[1:])) hypothetical function definition s oops: 1 'ae' s oops: 1 'e' s oops: 1 '' s oops: 1 '' s oops: 1 '' ... [lots of copies of the same message] RuntimeError: maximum recursion depth exceeded

Alternate implementation

def num_es2(s):

"""Returns: number of ‘e’s in . Precond: a string"""

# Strategy: break into two smaller strings, recur on both.

# base case: cannot break into two smaller strings

if (len(s) <= 1):

return (1 if s == 'e' else 0)

# recursive case: choose a random breakpoint

i = random.randrange(1:len(s) – 1)

return num_es2(s[:i]) + num_es2(s[i:])

How to Think About Recursive Functions

1. Have a precise function specification.

 Test cases generally handy here

2. Recursive case(s):

 Verify recursive cases with the specification

3. Reduction:

 Arguments of calls must somehow get “smaller”, so each recursive call gets closer to a base case

4. Base case(s):

 When the recursive case doesn't apply  When the argument values are as "small" as possible  When the answer is determined with little calculation.

Example: Palindromes

def ispalindrome(s):! """Returns: True if string s is a palindrome, False otherwise"""" if len(s) < 2:" return True

can check 1

st against last character, then interior (see posted code for solutions)

Example: Reversing a String

• Precise Specification :

 Returns: reverse of s

• Solving with recursion

 Suppose we can reverse  a smaller string (e.g., one fewer character)  Can we use that solution to reverse whole string? H e l l o! ! o l l e H e l l o! ! o l l e

H