Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from operator import add, sub, mul, truediv
- OPERATORS = {'+': (add, 0), '-': (sub, 0),
- '*': (mul, 1), '/': (truediv, 1)}
- def calc_in_polish(exp: list) -> float:
- """
- >>> calc_in_polish([5, 2, '*', 10, 5, '*', '+'])
- 60.0
- """
- stack = []
- for i in exp:
- operation = OPERATORS.get(i)
- if operation:
- a = stack.pop()
- b = stack.pop()
- stack.append(operation[0](b, a))
- else:
- stack.append(i)
- return stack.pop()
- def str_to_exp(raw_exp: str) -> list:
- """
- >>> str_to_exp('1 + 22.0 * 110')
- [1.0, '+', 22.0, '*', 110.0]
- """
- res = []
- tmp_num = ''
- for i in raw_exp:
- if i.isnumeric() or i == '.':
- tmp_num += i
- elif i in OPERATORS or i in '()':
- if tmp_num:
- res.append(float(tmp_num))
- tmp_num = ''
- res.append(i)
- if tmp_num:
- res.append(float(tmp_num))
- return res
- def to_polish(exp: list) -> list:
- """
- >>> to_polish([5, '*', 2, '+', 10, '*', 5])
- [5, 2, '*', 10, 5, '*', '+']
- """
- op_stack = []
- result = []
- for token in exp:
- if type(token) is float:
- result.append(token)
- elif token in OPERATORS:
- while op_stack and op_stack[-1] != '(' and OPERATORS[token][1] <= OPERATORS[op_stack[-1]][1]:
- result.append(op_stack.pop())
- op_stack.append(token)
- elif token == ')':
- while op_stack:
- op = op_stack.pop()
- if op == '(':
- break
- result.append(op)
- elif token == '(':
- op_stack.append(token)
- result.extend(op_stack[::-1])
- return result
- def calc(raw_exp: str) -> float:
- """
- >>> _eval('5 * 2 + 10 * 5')
- 60.0
- """
- exp = str_to_exp(raw_exp)
- polish = to_polish(exp)
- res = calc_in_polish(polish)
- print('raw:\t', raw_exp)
- print('parsed:\t', exp)
- print('polish:\t', polish)
- print('result:\t', res)
- return res
- calc('5 * (2 + 10) * 5')
Add Comment
Please, Sign In to add comment