Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. from pythonds import Stack
  2. #function to change infix notation to postfix notation
  3.  
  4. def infixToPostfix(expression):
  5.  
  6. #creating a dictionary name prec which compares the keys and checks for precedence associative rule
  7. prec = {}
  8.  
  9. #give '*' and '/' a value of 3 and '+' and '-' value of 2 and '(' a value of 1
  10.  
  11. prec["*"] = 3
  12. prec["/"] = 3
  13. prec["+"] = 2
  14. prec["-"] = 2
  15. prec["("] = 1
  16.  
  17. #creating a stack name store
  18. store = Stack()
  19.  
  20. #creating an empty list name
  21. postfix_list = []
  22.  
  23. #tokenList splits each passed elements to check for comparison
  24. tokenList = expression.split()
  25.  
  26. #check for the next item in the expression
  27. for counter in tokenList:
  28. #if the item existing is in the below list push to the list
  29.  
  30. if counter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or counter in "0123456789":
  31. postfix_list.append(counter)
  32. elif counter == '(':
  33. store.push(counter)
  34. elif counter == ')':
  35. topToken = store.pop()
  36. while topToken != '(':
  37. postfix_list.append(topToken)
  38. topToken = store.pop()
  39. else:
  40. while (not store.isEmpty()) and \
  41. (prec[store.peek()] >= prec[counter]):
  42. postfix_list.append(store.pop())
  43. store.push(counter)
  44.  
  45. while not store.isEmpty():
  46. postfix_list.append(store.pop())
  47. return " ".join(postfix_list)
  48.  
  49. print(infixToPostfix("A * B + C * D"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement