|
| 1 | +""" |
| 2 | +Python3 program to evaluate a prefix expression. |
| 3 | +""" |
| 4 | + |
| 5 | +calc = { |
| 6 | + "+": lambda x, y: x + y, |
| 7 | + "-": lambda x, y: x - y, |
| 8 | + "*": lambda x, y: x * y, |
| 9 | + "/": lambda x, y: x / y, |
| 10 | +} |
| 11 | + |
| 12 | + |
| 13 | +def is_operand(c): |
| 14 | + """ |
| 15 | + Return True if the given char c is an operand, e.g. it is a number |
| 16 | +
|
| 17 | + >>> is_operand("1") |
| 18 | + True |
| 19 | + >>> is_operand("+") |
| 20 | + False |
| 21 | + """ |
| 22 | + return c.isdigit() |
| 23 | + |
| 24 | + |
| 25 | +def evaluate(expression): |
| 26 | + """ |
| 27 | + Evaluate a given expression in prefix notation. |
| 28 | + Asserts that the given expression is valid. |
| 29 | +
|
| 30 | + >>> evaluate("+ 9 * 2 6") |
| 31 | + 21 |
| 32 | + >>> evaluate("/ * 10 2 + 4 1 ") |
| 33 | + 4.0 |
| 34 | + """ |
| 35 | + stack = [] |
| 36 | + |
| 37 | + # iterate over the string in reverse order |
| 38 | + for c in expression.split()[::-1]: |
| 39 | + |
| 40 | + # push operand to stack |
| 41 | + if is_operand(c): |
| 42 | + stack.append(int(c)) |
| 43 | + |
| 44 | + else: |
| 45 | + # pop values from stack can calculate the result |
| 46 | + # push the result onto the stack again |
| 47 | + o1 = stack.pop() |
| 48 | + o2 = stack.pop() |
| 49 | + stack.append(calc[c](o1, o2)) |
| 50 | + |
| 51 | + return stack.pop() |
| 52 | + |
| 53 | + |
| 54 | +# Driver code |
| 55 | +if __name__ == "__main__": |
| 56 | + test_expression = "+ 9 * 2 6" |
| 57 | + print(evaluate(test_expression)) |
| 58 | + |
| 59 | + test_expression = "/ * 10 2 + 4 1 " |
| 60 | + print(evaluate(test_expression)) |
0 commit comments