Reviewing Recursion

Recursive blue shirt

How can we solve this recursively?

The first person looks behind them:

Recursion and cases: Every recursive algorithm involves at least two cases:

Key idea: In a recursive piece of code, you handle a small part of the overall task yourself (usually the work involves modifying the results of the smaller problems), then make a recursive call to handle the rest.

Ask yourself, "how is ths task self-similar?"

Recursion Tips

Three rules of recursion

Recursive Program structure

def recursiveFunc(...):
  if (test for simple case): # base case 
    # Compute the solution without recursion 
  else:  # recursive case
    # 1. Break the problem into  subproblems of the same form 
    # 2. Call  recursiveFunc() on each  self-similar  subproblem
    # 3. Reassamble the results of the subproblems

Recursion with multiple base cases

Show a graphical picture of a pair of rabbits (A), they mate after one month, and generate another pair (B) after two months. After three months, the original pair produces another pair (C); while pair B mates. After four months, both pairs A and B, produce two pairs (D and E), while C mates. And so on...

Let's work out the numbers:

Fibonacci

def fib(x):
  """assume x an int >= 0
     returns Fibonacci of x"""
  if x == 0 or x == 1:
    return 1
  else:
    return fib(x-1) + fib(x-2)

Recursion on Non-Numerics

Solving recursively?

Example

def isPalindrome(s):
  def toChars(s):
    s = s.lower()
    ans = ''
    for c in s:
      if c in 'abcdefghijklmnopqrstuvwxyz':
        ans = ans + c
    return ans

  def isPal(s):
    if len(s) <= 1:
      return True
    else:
      return s[0] == s[-1] and isPal(s[1:-1])

  return isPal(toChars(s))
This is an example of a divide and conquer algorithm.

Exercise: Write a function power that accepts integer parameters for a base and exponent and computes base ^ exponent.

Method:

//Assumes exp >= 0
def power(base, exp):
  if exp == 0:
    return 1
  else:
    return base * power(base, exp - 1)
Show the execution of power(5, 3);

Can we do better? Notice that x^18 = (x*x)^9; x^9=x*x^8

//Assumes exp >= 0
def power(base, exp):
  if exp == 0:
    return 1
  elif exp % 2 == 0:
    return power(base * base, exp/2) #recursive case 1
  elif:
    return base * power(base, exp - 1) #recursive case 2