Advertisement
sreejith2904

expression-parser

Jan 20th, 2022
1,075
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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(sub(3,4),1)"
  9.  
  10. # operator wont be a leaf. operands will be
  11. map = {'add':'a',
  12.        'sub': 's',
  13.        'mul': 'm',
  14.        'div': 'd'}
  15.  
  16. operator_map = {'a' : np.add,
  17.                 's' : np.subtract,
  18.                 'm' : np.multiply,
  19.                 'd' : np.divide}
  20.  
  21.  
  22. for word, initial in map.items():
  23.     input_ = input_.replace(word.lower(), initial)
  24.  
  25. tokens = list(input_)
  26.  
  27. def remove_items(test_list, item):
  28.     res = [i for i in test_list if i != item]
  29.     return res
  30.    
  31. tokens = remove_items(tokens, "(")
  32. tokens = remove_items(tokens, ")")
  33. tokens = remove_items(tokens, ",")
  34.  
  35. def evaluate(tmp, operator_index):
  36.  
  37.     operator = tmp[operator_index]
  38.     left = tmp[operator_index + 1]
  39.     right = tmp[operator_index + 2]
  40.  
  41.     if left.isdigit() and right.isdigit():
  42.         operator = operator_map[operator]
  43.         return operator(int(left), int(right))
  44.  
  45.     if not left.isdigit():
  46.         left = evaluate(tmp, operator_index+1)
  47.     if not right.isdigit():
  48.         right = evaluate(tmp, operator_index+2)
  49.     operator = operator_map[operator]
  50.     return operator(int(left), int(right))
  51.        
  52. print("Expression ", input_, " evaluated to: ", evaluate(tokens, 0))
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement