[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

parenthesized subexpression is popped and evaluated ((3 4), then (1 + 12)), and 13
is displayed in the entry field. On pressing “eval,” the rest is evaluated ((3
13), (1 +39)),
and the final result (40) is shown. This result in the entry field itself becomes the left
operand of a future operator.


4) Entered keys: "1 + 3 * ( 1 + 3 * 4 ) <eval>" [result = 40]

(['+', '*', '(', '+', '*'], ['1', '3', '1', '3', '4']) [on ')']
(['+', '*', '(', '+'], ['1', '3', '1', '12']) [displays "13"]
(['+', '*'], ['1', '3', '13']) [on 'eval']
(['+'], ['1', '39'])

In fact, any temporary result can be used again: if we keep pressing an operator button
without typing new operands, it’s reapplied to the result of the prior press—the value
in the entry field is pushed twice and applied to itself each time. Press * many times
after entering 2 to see how this works (e.g., 2**). On the first , it pushes 2 and the
. On the next , it pushes 2 again from the entry field, pops and evaluates the stacked
(2 2), pushes back and displays the result, and pushes the new . And on each following
*, it pushes the currently displayed result and evaluates again, computing successive
squares.


Figure 19-6 shows how the two stacks look at their highest level while scanning the
expression in the prior example trace. On each reduction, the top operator is applied
to the top two operands and the result is pushed back for the operator below. Because
of the way the two stacks are used, the effect is similar to converting the expression to
a string of the form +13(+134 and evaluating it right to left. In other cases, though,
parts of the expression are evaluated and displayed as temporary results along the way,
so it’s not simply a string conversion process.


Figure 19-6. Evaluation stacks: 1 + 3 (1 + 3 4)


Finally, the next example’s string triggers an error. PyCalc is casual about error han-
dling. Many errors are made impossible by the algorithm itself, but things such as
unmatched parentheses still trip up the evaluator. Instead of trying to detect all possible
error cases explicitly, a general try statement in the reduce method is used to catch
them all: expression errors, numeric errors, undefined name errors, syntax errors, and
so on.


1468 | Chapter 19: Text and Language

Free download pdf