MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / evaluate

Function evaluate

data_structures/stacks/prefix_evaluation.py:26–55  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

24
25
26def 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
58def evaluate_recursive(expression: list[str]):

Callers 1

Calls 4

is_operandFunction · 0.85
splitMethod · 0.80
appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected