Advertisement
Jbears

Untitled

Dec 10th, 2021
760
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ExpressionEvaluator(object):
  2.     def __init__(self, expressions):
  3.         self.values = {}
  4.         for expression in expressions:
  5.             node, right_side = expression.split(" = ")
  6.             self.values[node] = right_side
  7.    
  8.    
  9.     def evaluate(self, node, path=set()):
  10.         expr_val = self.values[node]
  11.  
  12.         if self._expr_val_is_terminal(expr_val):
  13.             return expr_val
  14.  
  15.         # we're seeing a node again and we weren't
  16.         # able to evaluate it, so we have a cycle.
  17.         if node in path:
  18.             self.values[node] = "IMPOSSIBLE"
  19.             return self.values[node]
  20.  
  21.         # visit the current node
  22.         path.add(node)
  23.  
  24.         if self._expr_val_has_operator(expr_val):
  25.            
  26.             left_node, op, right_node = expr_val.split(" ")
  27.            
  28.             # try to evaluate left side
  29.             left_val = self.evaluate(left_node, path)
  30.             if left_val == "IMPOSSIBLE":
  31.                 self.values[node] = "IMPOSSIBLE"
  32.                 return self.values[node]
  33.            
  34.             # try to evaluate right side
  35.             right_val = self.evaluate(right_node, path)
  36.             if right_val == "IMPOSSIBLE":
  37.                 self.values[node] = "IMPOSSIBLE"
  38.                 return self.values[node]
  39.            
  40.             # update the value for the current node
  41.             self.values[node] = self._calculate_value(op, left_val, right_val)
  42.             return self.values[node]
  43.  
  44.         self.values[node] = self.evaluate(expr_val, path)
  45.         return self.values[node]
  46.  
  47.     def _calculate_value(self, op, a, b):
  48.         operations =  {"+": lambda a, b: a + b,
  49.                        "-": lambda a, b: a - b}
  50.         return str(operations[op](int(a), int(b)))
  51.  
  52.     def _expr_val_has_operator(self, expr_val):
  53.         return "+" in expr_val or "-" in expr_val
  54.  
  55.     def _expr_val_is_terminal(self, expr_val):
  56.         return (expr_val.isnumeric() or expr_val[0] == "-")
  57.  
  58.  
  59. expressions = [
  60.     "T1 = 1",
  61.     "T2 = 4",
  62.     "T3 = T1 + T4",
  63.     "T4 = T1 - T2",
  64.     "T5 = T6 + T1",
  65.     "T6 = T5",
  66.     "T7 = T4 + T3"
  67. ]
  68. exp_evaluator = ExpressionEvaluator(expressions)
  69. print(exp_evaluator.evaluate("T5"))
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement