Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pythonds import Stack
- #function to change infix notation to postfix notation
- def infixToPostfix(expression):
- #creating a dictionary name prec which compares the keys and checks for precedence associative rule
- prec = {}
- #give '*' and '/' a value of 3 and '+' and '-' value of 2 and '(' a value of 1
- prec["*"] = 3
- prec["/"] = 3
- prec["+"] = 2
- prec["-"] = 2
- prec["("] = 1
- #creating a stack name store
- store = Stack()
- #creating an empty list name
- postfix_list = []
- #tokenList splits each passed elements to check for comparison
- tokenList = expression.split()
- #check for the next item in the expression
- for counter in tokenList:
- #if the item existing is in the below list push to the list
- if counter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or counter in "0123456789":
- postfix_list.append(counter)
- elif counter == '(':
- store.push(counter)
- elif counter == ')':
- topToken = store.pop()
- while topToken != '(':
- postfix_list.append(topToken)
- topToken = store.pop()
- else:
- while (not store.isEmpty()) and \
- (prec[store.peek()] >= prec[counter]):
- postfix_list.append(store.pop())
- store.push(counter)
- while not store.isEmpty():
- postfix_list.append(store.pop())
- return " ".join(postfix_list)
- print(infixToPostfix("A * B + C * D"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement