Advertisement
Zelatrix

shunting_yard

Jan 15th, 2021 (edited)
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.93 KB | None | 0 0
  1. import re
  2.  
  3.  
  4. def precedence(operator):
  5.     if operator == '+':
  6.         return 2
  7.     elif operator == '-':
  8.         return 2
  9.     elif operator == '*':
  10.         return 3
  11.     elif operator == '/':
  12.         return 3
  13.  
  14.  
  15. def associativity(operator):
  16.     if operator in ['*', '/', '+', '-']:
  17.         return "left"
  18.     elif operator in ['^']:
  19.         return "right"
  20.  
  21.  
  22. def reverse_polish(formula):
  23.     tokens = formula.split(" ")
  24.     operators = []  # The operator stack
  25.     output = []
  26.  
  27.     for i in range(len(tokens)):
  28.         # If the token is a number
  29.         if re.match("[0-9]", tokens[i]):
  30.             output += tokens[i]
  31.                 while re.match("[-+*/]", operators[-1]) and (precedence(operators[0]) > precedence(tokens[i])) or ((precedence(operators[0]) == precedence(tokens[i])) and associativity(tokens[0]) == "left") and (tokens[0] != '('):
  32.                         print(operators)
  33.                         # pop the operator off of the operator stack and onto the output queue
  34.                         output += operators.pop()
  35.                 # push it onto the operator stack
  36.                 operators += tokens[i]
  37.             # If the current token is a left parenthesis, push it onto the operator stack
  38.             elif tokens[i] == '(':
  39.                 operators += tokens[i]
  40.             # If the current token is a right parenthesis, then keep popping operators off the operator stack until you
  41.             # find the corresponding left parenthesis
  42.             elif tokens[i] == ')':
  43.                 while operators[0] != '(':
  44.                     output += operators.pop()
  45.                 if operators[0] == '(':
  46.                     operators.pop()
  47.     # There are still operators on the operator stack at this point
  48.     while operators:
  49.         output += operators.pop()
  50.     print("".join(output))
  51.     print(operators)
  52.  
  53.  
  54. def main():
  55.     reverse_polish("3 + 4 * 2")
  56.  
  57.  
  58. if __name__ == "__main__":
  59.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement