Recursion

Inductive reasoning

def mult_iter(a, b):
  result = 0
  while b > 0:
    result += a
    b -= 1
  return result

def mult(a, b):
  if b == 1:
    return a
  else:
    return a + mult(a, b-1)

Mathematical Induction

Example of Induction

Relevance to code?

def mult(a, b):
  if b == 1:
    return a
  else:
    return a + mult(a, b-1)
Same logic applies:

Towers of Hanoi. The story

Show some examples of a small number of disks. Having seen a set of examples of different sized stacks, how would you write a program to print out the right set of moves? Think recursively:
def printMove(fr, to):
  print('move from ' + str(fr) + ' to ' + str(to))

def Towers(n, fr, to, spare):
  if n == 1:
    printMove(fr, to)
  else:
    Towers(n-1, fr, spare, to)
    Towers(1, fr, to, spare)
    Towers(n-1, spare, to, fr)

Showed this on pythontutor.com for n=2 and n=3

Prove inductively that the number of moves of Towers(n, ...) is 2**n-1: