Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- def precedence(operator):
- if operator == '+':
- return 2
- elif operator == '-':
- return 2
- elif operator == '*':
- return 3
- elif operator == '/':
- return 3
- def associativity(operator):
- if operator in ['*', '/', '+', '-']:
- return "left"
- elif operator in ['^']:
- return "right"
- def reverse_polish(formula):
- tokens = formula.split(" ")
- operators = [] # The operator stack
- output = []
- for i in range(len(tokens)):
- # If the token is a number
- if re.match("[0-9]", tokens[i]):
- output += tokens[i]
- 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] != '('):
- print(operators)
- # pop the operator off of the operator stack and onto the output queue
- output += operators.pop()
- # push it onto the operator stack
- operators += tokens[i]
- # If the current token is a left parenthesis, push it onto the operator stack
- elif tokens[i] == '(':
- operators += tokens[i]
- # If the current token is a right parenthesis, then keep popping operators off the operator stack until you
- # find the corresponding left parenthesis
- elif tokens[i] == ')':
- while operators[0] != '(':
- output += operators.pop()
- if operators[0] == '(':
- operators.pop()
- # There are still operators on the operator stack at this point
- while operators:
- output += operators.pop()
- print("".join(output))
- print(operators)
- def main():
- reverse_polish("3 + 4 * 2")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement