Evaluate a given expression in prefix notation. Asserts that the given expression is valid. >>> evaluate("+ 9 * 2 6") 21 >>> evaluate("/ * 10 2 + 4 1 ") 4.0 >>> evaluate("2") 2 >>> evaluate("+ * 2 3 / 8 4") 8.0
(expression)
| 24 | |
| 25 | |
| 26 | def evaluate(expression): |
| 27 | """ |
| 28 | Evaluate a given expression in prefix notation. |
| 29 | Asserts that the given expression is valid. |
| 30 | |
| 31 | >>> evaluate("+ 9 * 2 6") |
| 32 | 21 |
| 33 | >>> evaluate("/ * 10 2 + 4 1 ") |
| 34 | 4.0 |
| 35 | >>> evaluate("2") |
| 36 | 2 |
| 37 | >>> evaluate("+ * 2 3 / 8 4") |
| 38 | 8.0 |
| 39 | """ |
| 40 | stack = [] |
| 41 | |
| 42 | # iterate over the string in reverse order |
| 43 | for c in expression.split()[::-1]: |
| 44 | # push operand to stack |
| 45 | if is_operand(c): |
| 46 | stack.append(int(c)) |
| 47 | |
| 48 | else: |
| 49 | # pop values from stack can calculate the result |
| 50 | # push the result onto the stack again |
| 51 | o1 = stack.pop() |
| 52 | o2 = stack.pop() |
| 53 | stack.append(operators[c](o1, o2)) |
| 54 | |
| 55 | return stack.pop() |
| 56 | |
| 57 | |
| 58 | def evaluate_recursive(expression: list[str]): |
no test coverage detected