Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # (A + B) * (C + D)
- # https://gist.github.com/mycodeschool/7867739
- class Stack:
- def __init__(self):
- self.top = -1
- self.stack = []
- def push(self, val):
- self.top += 1
- self.stack.append(val)
- def getTop(self):
- return self.stack[-1]
- def pop(self):
- self.top -= 1
- return self.stack.pop()
- def str(self):
- print("Current Stack: ", self.stack)
- print('Current Top: ', self.top)
- def empty(self):
- if self.top == -1 and len(self.stack) == 0:
- return True
- return False
- def isOperator(x):
- if x == "+" or x == '-' or x == '*' or x == '/' or x == '^':
- return True
- return False
- def isOperand(x):
- if x >= 'A' and x <= 'Z':
- return True
- elif x >= 'a' and x <= 'z':
- return True
- return False
- def isOpeningParam(s):
- if s == '(':
- return True
- return False
- def isClosingParam(s):
- if s == ')':
- return True
- return False
- def getOpWeight(op):
- weight = -1
- if op == '+' or op == '-':
- weight = 1
- elif op == '*' or op == '/':
- weight = 2
- elif op == "^":
- weight = 3
- return weight
- def hasHigherPrec(op1, op2):
- op1 = getOpWeight(op1)
- op2 = getOpWeight(op2)
- if op1 >= op2:
- return True
- return False
- def convert_to_postfix(exp):
- stack = Stack()
- stack.push('(')
- exp += ')'
- result = ''
- for i in exp:
- if isOperand(i):
- result += i
- elif isOperator(i):
- while ((not stack.empty()) and isOperator(stack.getTop()) and hasHigherPrec(stack.getTop(), i)):
- result += stack.pop()
- stack.push(i)
- #param control
- elif isOpeningParam(i):
- stack.push(i)
- elif isClosingParam(i):
- while not isOpeningParam(stack.getTop()):
- result += stack.pop()
- #extram param pop()
- stack.pop()
- return result
- if __name__ == '__main__':
- exp = "a+b*(c^d-e)^(f+g*h)-i"
- res = convert_to_postfix(exp)
- print(res)
Add Comment
Please, Sign In to add comment