Advertisement
oleh_korkh

Untitled

Feb 3rd, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.02 KB | None | 0 0
  1.  
  2. """
  3.  
  4. x = Formula('2.34 + valueX * 8 - 49879 * (valueY + 178)')
  5. result = x.execute(valueX=2, valueY=3)
  6.  
  7.  
  8. ['2.34', '+', 'valueX', '*', '8', '-', '49879', '*',
  9. '(', 'valueY', '+', '178', ')']
  10.  
  11. ['valueX', '8', '*', '2.34', '+', 'valueY', '178',
  12. '+', '49879', '*', '-']
  13.  
  14. """
  15.  
  16.  
  17. class Formula:
  18.     OPERATORS = ['+', '-', '*', '/', '**', '(', ')']
  19.  
  20.     def __init__(self, source):
  21.         self.source = source.strip().replace(' ', '')
  22.         self.tokens = []
  23.         self.rpn = []
  24.         self.analyze_syntax()
  25.         self.compile()
  26.  
  27.     def analyze_syntax(self):
  28.         tokens = []
  29.         token = ''
  30.         for i, ch in enumerate(self.source):
  31.             if ch not in self.OPERATORS:
  32.                 token += ch
  33.             else:
  34.                 if self.source[i:i+2] == '**':
  35.                     continue
  36.                 if token:
  37.                     tokens.append(token)
  38.                     token = ''
  39.                 if self.source[i-1:i+1] == '**':
  40.                     tokens.append('**')
  41.                 else:
  42.                     tokens.append(ch)
  43.             print(ch, token, tokens)
  44.         if token:
  45.             tokens.append(token)
  46.         self.tokens = tokens
  47.         print(tokens)
  48.  
  49.     def op_prec(self, operator):
  50.         if operator in '+-':
  51.             return 1
  52.         elif operator in '*/':
  53.             return 2
  54.         elif operator == '**':
  55.             return 3
  56.         elif operator == '(':
  57.             return 100
  58.  
  59.     def compile(self):
  60.         result_queue = []
  61.         operator_stack = []
  62.  
  63.         for token in self.tokens:
  64.             if token == ')':
  65.                 while operator_stack and operator_stack[-1] != '(':
  66.                     result_queue.append(operator_stack.pop())
  67.                 operator_stack.pop()
  68.             elif token in self.OPERATORS:
  69.                 if operator_stack:
  70.                     if self.op_prec(token) < self.op_prec(operator_stack[-1]):
  71.                         while self.op_prec(token) < self.op_prec(operator_stack[-1]) and operator_stack[-1] != '(':
  72.                             result_queue.append(operator_stack.pop())
  73.                         operator_stack.append(token)
  74.                     else:
  75.                         operator_stack.append(token)
  76.                 else:
  77.                     operator_stack.append(token)
  78.             else:
  79.                 result_queue.append(token)
  80.             # print(token, operator_stack, result_queue)
  81.  
  82.         while operator_stack:
  83.             result_queue.append(operator_stack.pop())
  84.  
  85.         self.rpn = result_queue
  86.  
  87.     def execute(self, **kwargs):
  88.         def get_value(value):
  89.             if value.isdigit():
  90.                 return int(value)
  91.             else:
  92.                 try:
  93.                     return float(value)
  94.                 except ValueError:
  95.                     if value in self.OPERATORS:
  96.                         return value
  97.                     else:
  98.                         return kwargs[value]
  99.  
  100.         expr = [get_value(x) for x in self.rpn]
  101.         i = 0
  102.         while len(expr) > 1:
  103.             if expr[i] in self.OPERATORS:
  104.                 result = None
  105.                 if expr[i] == '+':
  106.                     result = expr[i-2] + expr[i-1]
  107.                 elif expr[i] == '-':
  108.                     result = expr[i-2] - expr[i-1]
  109.                 elif expr[i] == '*':
  110.                     result = expr[i-2] * expr[i-1]
  111.                 elif expr[i] == '/':
  112.                     result = expr[i-2] / expr[i-1]
  113.                 elif expr[i] == '**':
  114.                     result = expr[i-2] ** expr[i-1]
  115.  
  116.                 expr[i] = result
  117.                 del expr[i-2:i]
  118.                 i = 0
  119.             else:
  120.                 i += 1
  121.             # print(expr)
  122.  
  123.         return expr[0]
  124.  
  125.  
  126. # x = Formula('2.34 + valueX * 8 - 49879 * (valueY + 178)')
  127. # print(x.source)
  128. # print(x.tokens)
  129. # print(x.rpn)
  130. # print(x.execute(valueX=2, valueY=3))
  131. # print(2.34 + 2 * 8 - 49879 * (3 + 178))
  132.  
  133.  
  134. x = Formula(input('>> '))
  135.  
  136. for i in range(1, 11):
  137.     print(x.execute(X=i))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement