Pregunta de entrevista de Microsoft

How to write an evaluator for a string like "(1+3 * ( 5 / 4)) and get a numeric result.

Respuestas de entrevistas

Anónimo

5 may 2009

There's an easier way that doesn't require a grammar. Use two stacks: an operator stack, and an operand stack. Alternate between parsing operands and operators, pushing onto the appropriate stack as you go. Whenever you encounter an operator that has precedence less than or equal to the operator at the top of the operator stack, pop that operator and the topmost two operands, evaluate, and push the result onto the operand stack. You can treat the "end of string" as though it were an operator of the lowest precedence. When you are done, the operator stack should be empty, and the operand stack should contain one element, the result. To handle parentheses, treat the left paren as though it were an operator, except that you'll always push it immediately without evaluating anything. Then treat the left paren as though it were an operator of the lowest precedence. This forces you to evaluate only within that paren group until you encounter its corresponding right paren, at which point you'll pop and evaluate until you get to the left paren.

3

Anónimo

21 nov 2009

Pseudo code for ad hoc LL(1) recursive parser: eval_atom: if (next is number): consume and return number if (next is '(': consume and return eval_expr(), consume ')' and return the result eval_mul: result = eval_atom() while (next is '*' or '/') consume, result = result * (or /) eval_atom() - depending of the operator return result eval_expr: result = eval_mul while (next is '+' or '-') consume, result = result + (or -) eval_mul() - depending of the operator return result Above represents parsing grammar: expr: expr_mul | expr_mul ('+' | '-') expr expr_mul: atom | atom ('*' | '/') expr_mul atom: integer | '(' expr ')'

Anónimo

5 may 2009

First make up a Context Free Grammar for the expression. Next create an Abstract Syntax Tree using either LL(k) parsing or Recursive Decent Parsing. Then simply walk the leaf nodes of the AST and evaluate based on their parent functions.