Advertisement
sreejith2904

expression evaluator

Jan 20th, 2022
904
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. # input -> "sub(1,3)" output -> -2
  2. # operations take only 2 params. commands may be nested.
  3. # ie. add(sub(3,4), 1), sub(add(238943, 2343), add(1, sub(323, 43)))
  4. import numpy as np
  5.  
  6.  
  7. operators = ['add', 'sub', 'mul', 'div']
  8. input_ = "add(3,4)"
  9. #input_ = "add(sub(3,4),1)"
  10.  
  11.  
  12.  
  13. # operator wont be a leaf. operands will be
  14. map = {'add':'a',
  15.        'sub': 's',
  16.        'mul': 'm',
  17.        'div': 'd'}
  18.  
  19. operator_map = {'a' : np.add,
  20.                 's' : np.subtract,
  21.                 'm' : np.multiply,
  22.                 'd' : np.divide}
  23.  
  24.  
  25. for word, initial in map.items():
  26.     input_ = input_.replace(word.lower(), initial)
  27.  
  28. tokens = list(input_)
  29.  
  30. def remove_items(test_list, item):
  31.     res = [i for i in test_list if i != item]
  32.     return res
  33.    
  34. tokens = remove_items(tokens, "(")
  35. tokens = remove_items(tokens, ")")
  36. tokens = remove_items(tokens, ",")
  37.  
  38. print(tokens)
  39.  
  40.  
  41.  
  42. def evaluate(tmp):
  43.  
  44.     for index, element in enumerate(tmp):
  45.         if element in ['a', 's', 'm', 'd']:
  46.             operator = operator_map[element]
  47.             operand_l = tmp[2*index+1]
  48.             operand_r = tmp[2*index+2]
  49.  
  50.             if operand_l.isdigit() and operand_r.isdigit():
  51.                 return operator(int(operand_l), int(operand_r))
  52.             # elif operand_l isdigit():
  53.             #     evaluate()
  54.             #     return operator(operand_l, )
  55.            
  56.  
  57.    
  58.  
  59. print(evaluate(tokens))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement