Guest User

Untitled

a guest
Nov 18th, 2017
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. def regex2post(regE): # Convert regular expression from infix to postfix
  2.  
  3. precedenceMap = {
  4. '(' : 1,
  5. ')' : 1,
  6. '?' : 2,
  7. '*' : 2,
  8. '+' : 2,
  9. '.' : 3
  10. }
  11.  
  12.  
  13. postfix_reg = ''
  14. operator_stack = Stack()
  15. print(regE)
  16. for c in regE:
  17. if c.isalpha():
  18. postfix_reg += c
  19. elif (c == '*' or c == '+' or c == '?' or c == '.' or c == '(') and operator_stack.isEmpty():
  20. operator_stack.push(c)
  21. elif (c == '*' or c == '+' or c == '?' or c == '.' or c == '(' or c == ')') and not(operator_stack.isEmpty()):
  22. previous_operator = operator_stack.pop()
  23. print(previous_operator)
  24. if previous_operator != '(' and previous_operator != ')' and precedenceMap[previous_operator] >= precedenceMap[c]:
  25. postfix_reg += previous_operator
  26. operator_stack.push(c)
  27. if previous_operator == '(':
  28. operator_stack.push(previous_operator)
  29. operator_stack.push(c)
  30. if c == ')':
  31. previous_operator = operator_stack.pop()
  32. while not (previous_operator == '('):
  33. postfix_reg += previous_operator
  34. previous_operator = operator_stack.pop()
  35.  
  36. while not(operator_stack.isEmpty()):
  37. postfix_reg += operator_stack.pop()
  38.  
  39. return postfix_reg
Add Comment
Please, Sign In to add comment