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)
mult_iter terminates because b is initially positive, and decreases by 1 each time around loop; thus must eventually become less than 1.mult called with b=1 has no recursive call and stopsmult called with b>1 makes a recursive call with a smaller version of b; must eventually reach call with b=1.Mathematical Induction
n:
n is smallest value (e.g., n=0 or n=1).n, one
can show that it must be true for n+1.
Example of Induction
n=0, then LHS is 0 and RHS is 0*1/2=0, so truek, then need to show that
0+1+2+...+k+(k+1) = ((k+1)(k+2))/2
k(k+1)/2 + (k+1) by assumption that property holds for problem of size k.((k+1)(k+2))/2.n >= 0Relevance to code?
def mult(a, b):
if b == 1:
return a
else:
return a + mult(a, b-1)
Same logic applies:
mult must return correct answermult correctly returns an answer for problems of size smaller than b, then by the addition step, it must also return a correct answer for problem of size b.Towers of Hanoi. The story
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:
n=1, the number of moves is 1n=2, the number of moves is 1+1+1=3n=3, the number of moves is 3+1+3=7n=4, the number of moves is 7+1+7=7n is 2**n-1 (show by induction)