n0va_sa

Postfix

Sep 16th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. # (A + B) * (C + D)
  2. # https://gist.github.com/mycodeschool/7867739
  3. class Stack:
  4.     def __init__(self):
  5.         self.top = -1
  6.         self.stack = []
  7.  
  8.     def push(self, val):
  9.         self.top += 1
  10.         self.stack.append(val)
  11.  
  12.     def getTop(self):
  13.         return self.stack[-1]
  14.  
  15.     def pop(self):
  16.         self.top -= 1
  17.         return self.stack.pop()
  18.  
  19.     def str(self):
  20.         print("Current Stack: ", self.stack)
  21.         print('Current Top: ', self.top)
  22.  
  23.     def empty(self):
  24.         if self.top == -1 and len(self.stack) == 0:
  25.             return True
  26.         return False
  27.  
  28.  
  29. def isOperator(x):
  30.     if x == "+" or x == '-' or x == '*' or x == '/' or x == '^':
  31.         return True
  32.     return False
  33.  
  34. def isOperand(x):
  35.     if x >= 'A' and x <= 'Z':
  36.         return True
  37.     elif x >= 'a' and x <= 'z':
  38.         return True
  39.     return False
  40.  
  41. def isOpeningParam(s):
  42.     if s == '(':
  43.         return True
  44.     return False
  45.  
  46. def isClosingParam(s):
  47.     if s == ')':
  48.         return True
  49.     return False
  50.  
  51. def getOpWeight(op):
  52.     weight = -1
  53.     if op == '+' or op == '-':
  54.         weight = 1
  55.     elif op == '*' or op == '/':
  56.         weight = 2
  57.     elif op == "^":
  58.         weight = 3
  59.  
  60.     return weight
  61.  
  62.  
  63. def hasHigherPrec(op1, op2):
  64.     op1 = getOpWeight(op1)
  65.     op2 = getOpWeight(op2)
  66.     if op1 >= op2:
  67.         return True
  68.     return False
  69.  
  70. def convert_to_postfix(exp):
  71.     stack = Stack()
  72.     stack.push('(')
  73.     exp += ')'
  74.     result = ''
  75.     for i in exp:
  76.         if isOperand(i):
  77.             result += i
  78.         elif isOperator(i):
  79.             while ((not stack.empty()) and isOperator(stack.getTop()) and hasHigherPrec(stack.getTop(), i)):
  80.                 result += stack.pop()
  81.             stack.push(i)
  82.  
  83.  
  84.         #param control
  85.         elif isOpeningParam(i):
  86.             stack.push(i)
  87.  
  88.         elif isClosingParam(i):
  89.             while not isOpeningParam(stack.getTop()):
  90.                 result += stack.pop()
  91.             #extram param pop()
  92.             stack.pop()
  93.  
  94.     return result
  95.  
  96. if __name__ == '__main__':
  97.     exp = "a+b*(c^d-e)^(f+g*h)-i"
  98.     res = convert_to_postfix(exp)
  99.     print(res)
Add Comment
Please, Sign In to add comment