Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # input -> "sub(1,3)" output -> -2
- # operations take only 2 params. commands may be nested.
- # ie. add(sub(3,4), 1), sub(add(238943, 2343), add(1, sub(323, 43)))
- import numpy as np
- operators = ['add', 'sub', 'mul', 'div']
- input_ = "add(3,4)"
- #input_ = "add(sub(3,4),1)"
- # operator wont be a leaf. operands will be
- map = {'add':'a',
- 'sub': 's',
- 'mul': 'm',
- 'div': 'd'}
- operator_map = {'a' : np.add,
- 's' : np.subtract,
- 'm' : np.multiply,
- 'd' : np.divide}
- for word, initial in map.items():
- input_ = input_.replace(word.lower(), initial)
- tokens = list(input_)
- def remove_items(test_list, item):
- res = [i for i in test_list if i != item]
- return res
- tokens = remove_items(tokens, "(")
- tokens = remove_items(tokens, ")")
- tokens = remove_items(tokens, ",")
- print(tokens)
- def evaluate(tmp):
- for index, element in enumerate(tmp):
- if element in ['a', 's', 'm', 'd']:
- operator = operator_map[element]
- operand_l = tmp[2*index+1]
- operand_r = tmp[2*index+2]
- if operand_l.isdigit() and operand_r.isdigit():
- return operator(int(operand_l), int(operand_r))
- # elif operand_l isdigit():
- # evaluate()
- # return operator(operand_l, )
- print(evaluate(tokens))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement