parsing - Postfix expression parser in Python -
i trying complete program running few things need with. need trying to: make sure user input correct , error test. like.....
if token == "" or token == " "
i not sure how make sure user input correct.
assignment:
write program (postfix.py) extracts postfix expression user , evaluates described in class. program should extract expression user via standard input. expression should formatted such there @ least 1 blank space between each operator , operand. example,
enter postfix expression:
5 6 * 13 2 * +
assume operators , operands valid. operands should integer values while valid operators include+ - / * %
after extracting expression, use
split()
method on string split individual tokens stored in python list. note multi-digit operand (i.e.13
) considered single token.the postfix expression should printed standard output, 1 token @ time, being evaluated. in addition, if expression valid, result should printed on next line following expression shown below
5 6 * 13 2 * + = 56
if expression invalid, stop evaluating expression once determined there error , print 3 dollar signs. print error message on next line indicate error. example, if there many operators given operands encountered, program should produce results shown below
enter postfix expression: 17 6 / + 8 * 17 6 / + $$$ error: insufficient number of operands.
when there few operators given operands, program should produce results shown below
enter postfix expression: 17 6 / 25 5 + 17 6 / 25 5 + $$$ error: insufficient number of operators.
my code:
input("enter postfix expression: ") operorlist("*, /, -, +, %") def postfixeval(postfixexpr): operandstack = stack() tokenlist = postfixexpr.split() token in tokenlist: if token in "0123456789": operandstack.push(int(token)) else: operand2 = operandstack.pop() operand1 = operandstack.pop() result = domath(token,operand1,operand2) operandstack.push(result) return operandstack.pop() def domath(op, op1, op2): if op == "*": return op1 * op2 elif op == "/": return op1 / op2 elif op == "+": return op1 + op2 elif op == "%": return op1 % op2 else: return op1 - op2
the assignmment tells
assume operators , operands valid. operands should integer values while valid operators include
+
-
/
*
%
thus 1 can assume nothing else input, , errors happen many or not enough operands on stack, need test those.
the line
if token in "0123456789":
only checks if whole token substring of 0123456789
, a.k.a single digit, 01
, 4567
or so.
what want instead check whether token digits:
if token.isdigit(): ...
as too few operands, either 1 of pop
s throw exception indexerror
; you'd catch , report error:
try: operand2 = operandstack.pop() operand1 = operandstack.pop() except indexerror: # handle appropriately
similarly many operands mean operandstack
has more 1 item @ end, check len(operandstack)
; if greater 1 report "too many operands".
Comments
Post a Comment