Guest User

Untitled

a guest
Mar 18th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. from operator import add, sub, mul, truediv
  2.  
  3. OPERATORS = {'+': (add, 0), '-': (sub, 0),
  4. '*': (mul, 1), '/': (truediv, 1)}
  5.  
  6.  
  7. def calc_in_polish(exp: list) -> float:
  8. """
  9. >>> calc_in_polish([5, 2, '*', 10, 5, '*', '+'])
  10. 60.0
  11. """
  12. stack = []
  13. for i in exp:
  14. operation = OPERATORS.get(i)
  15. if operation:
  16. a = stack.pop()
  17. b = stack.pop()
  18. stack.append(operation[0](b, a))
  19. else:
  20. stack.append(i)
  21.  
  22. return stack.pop()
  23.  
  24.  
  25. def str_to_exp(raw_exp: str) -> list:
  26. """
  27. >>> str_to_exp('1 + 22.0 * 110')
  28. [1.0, '+', 22.0, '*', 110.0]
  29. """
  30. res = []
  31. tmp_num = ''
  32. for i in raw_exp:
  33. if i.isnumeric() or i == '.':
  34. tmp_num += i
  35. elif i in OPERATORS or i in '()':
  36. if tmp_num:
  37. res.append(float(tmp_num))
  38. tmp_num = ''
  39. res.append(i)
  40.  
  41. if tmp_num:
  42. res.append(float(tmp_num))
  43.  
  44. return res
  45.  
  46.  
  47. def to_polish(exp: list) -> list:
  48. """
  49. >>> to_polish([5, '*', 2, '+', 10, '*', 5])
  50. [5, 2, '*', 10, 5, '*', '+']
  51. """
  52. op_stack = []
  53. result = []
  54. for token in exp:
  55. if type(token) is float:
  56. result.append(token)
  57. elif token in OPERATORS:
  58. while op_stack and op_stack[-1] != '(' and OPERATORS[token][1] <= OPERATORS[op_stack[-1]][1]:
  59. result.append(op_stack.pop())
  60. op_stack.append(token)
  61. elif token == ')':
  62. while op_stack:
  63. op = op_stack.pop()
  64. if op == '(':
  65. break
  66. result.append(op)
  67. elif token == '(':
  68. op_stack.append(token)
  69.  
  70. result.extend(op_stack[::-1])
  71. return result
  72.  
  73.  
  74. def calc(raw_exp: str) -> float:
  75. """
  76. >>> _eval('5 * 2 + 10 * 5')
  77. 60.0
  78. """
  79. exp = str_to_exp(raw_exp)
  80. polish = to_polish(exp)
  81. res = calc_in_polish(polish)
  82.  
  83. print('raw:\t', raw_exp)
  84. print('parsed:\t', exp)
  85. print('polish:\t', polish)
  86. print('result:\t', res)
  87.  
  88. return res
  89.  
  90.  
  91. calc('5 * (2 + 10) * 5')
Add Comment
Please, Sign In to add comment