Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ExpressionEvaluator(object):
- def __init__(self, expressions):
- self.values = {}
- for expression in expressions:
- node, right_side = expression.split(" = ")
- self.values[node] = right_side
- def evaluate(self, node, path=set()):
- expr_val = self.values[node]
- if self._expr_val_is_terminal(expr_val):
- return expr_val
- # we're seeing a node again and we weren't
- # able to evaluate it, so we have a cycle.
- if node in path:
- self.values[node] = "IMPOSSIBLE"
- return self.values[node]
- # visit the current node
- path.add(node)
- if self._expr_val_has_operator(expr_val):
- left_node, op, right_node = expr_val.split(" ")
- # try to evaluate left side
- left_val = self.evaluate(left_node, path)
- if left_val == "IMPOSSIBLE":
- self.values[node] = "IMPOSSIBLE"
- return self.values[node]
- # try to evaluate right side
- right_val = self.evaluate(right_node, path)
- if right_val == "IMPOSSIBLE":
- self.values[node] = "IMPOSSIBLE"
- return self.values[node]
- # update the value for the current node
- self.values[node] = self._calculate_value(op, left_val, right_val)
- return self.values[node]
- self.values[node] = self.evaluate(expr_val, path)
- return self.values[node]
- def _calculate_value(self, op, a, b):
- operations = {"+": lambda a, b: a + b,
- "-": lambda a, b: a - b}
- return str(operations[op](int(a), int(b)))
- def _expr_val_has_operator(self, expr_val):
- return "+" in expr_val or "-" in expr_val
- def _expr_val_is_terminal(self, expr_val):
- return (expr_val.isnumeric() or expr_val[0] == "-")
- expressions = [
- "T1 = 1",
- "T2 = 4",
- "T3 = T1 + T4",
- "T4 = T1 - T2",
- "T5 = T6 + T1",
- "T6 = T5",
- "T7 = T4 + T3"
- ]
- exp_evaluator = ExpressionEvaluator(expressions)
- print(exp_evaluator.evaluate("T5"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement