postfix notation. Operands will be any number, operators are +, −, ∗ (no division). Operators

and operands will always be separated by spaces. A special operand, "answer", is taken to mean the

final answer of the previous expression.

Input will come in the form of several mathematical expressions, each on its own line, terminated

by a blank line. These expressions may be related to each other through the answer operand, but are

otherwise treated as separate expressions. It is possible for an expression to be invalid. For valid

expressions, evaluate the expression and output the final answer. For invalid expressions, output

'Invalid’. If the ans operand refers to an invalid expression, then the expression containing it is

also invalid.

My problem is the "answer" operand and checking Validity of any expression.

the code is:

import operator #import doctest expression = raw_input() class Stack : def initial(self): self.item = [] def push(self, item): self.item.append(item) def pop(self): return self.item.pop() def empty(self): return (self.item ==[]) arithmetics = {"+":"add","-":"sub","*":"mul"} def postfix (expression,stack=Stack(), operators = arithmetics): if not isinstance(expression, str): return for val in expression.split(" "): if operators.has_key(val): method = getattr(operator, operators.get(val)) if len(stack.items) < 2: return first_out_one = stack.pop() fisrt_one_two = stack.pop() operand = method(fisrt_one_two,fisrt_one_one) stack.push(operand) else: try: operand = int(val) stack.push(operand) except ValueError: continue return stack.pop() print postfix(expression,Stack(),arithmetics)]

This post has been edited by **baavgai**: 25 May 2011 - 08:18 AM

Reason for edit:: tags fixed