Parsing Expressions and Induction



Grammars for Algebraic Expressions



Prefix and Postfix Expression



Recognizing Prefix Expressions

 =  |   
 = + | - | * | /
 = a | b | c | ... | z



Finding the end of a Prefix Expressions

endPre (first, last) {
  if (first > last) return -1;
  ch = character at first;
  if (ch is an id) return first
  if (ch is not an operator)
    return -1;
  firstEnd = endPre (first + 1, last);
  if (firstSub >= 0) {
    return endPre (firstEnd + 1, last);
  }
  return -1;
}

Notes:


If time allows, box trace this pseudocode on blackboard, see p. 227-228 of book (but use different parameters on blackboard)



Evaluating a Prefix Expressions



Towers of Hanoi



Correctness of Factorial

fact (n) 
  if (n is 0) return 1;
  return n * fact (n - 1);



Cost of Towers of Hanoi

towers (n, src, dest, spare) 
  if (count is 1) move 1 from src to dest
  else
    towers (n - 1, src, spare, dest);
    move 1 from src to dest
    towers (n - 1, spare, dest, src);



Cost of Towers of Hanoi -- Math Induction