Skip to content

Instantly share code, notes, and snippets.

@debabrata100
Created September 15, 2018 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debabrata100/e8989ae331231fe565c18e795aedfc0b to your computer and use it in GitHub Desktop.
Save debabrata100/e8989ae331231fe565c18e795aedfc0b to your computer and use it in GitHub Desktop.
This python program illustrates how to write a python program to convert infix expression to postfix using python list as stack
def getOperatorWeight(op):
weights = {
'+': 1,
'-': 1,
'*': 2,
'/': 2,
'^': 3
}
return weights.get(op)
def isRightAssociative(op):
return op == '^'
def isOperand(c):
if c not in ['+','-','*','/','^','(',')','{','}']:
return True
return False
def isOperator(c):
if c in ['+','-','*','/','^']:
return True
return False
def isEmpty(stack):
return len(stack) == 0
def stackTop(stack):
return stack[len(stack)-1]
def HasHigherPriority(op1,op2):
op1_weight = getOperatorWeight(op1)
op2_weight = getOperatorWeight(op2)
if op1_weight == op2_weight:
if isRightAssociative(op1_weight): return False
return True
return op1_weight > op2_weight
def ConvertToPostfix(exp):
stack = []
postfixString = ''
for el in exp:
if isOperand(el):
postfixString += el
elif el == "(":
stack.append(el)
elif isOperator(el):
while not isEmpty(stack) and stackTop(stack) != '(' and HasHigherPriority( stackTop(stack), el):
postfixString += stackTop(stack)
stack.pop()
stack.append(el)
elif el == ")":
while not isEmpty(stack) and stackTop(stack) != '(':
postfixString += stackTop(stack)
stack.pop()
stack.pop()
while not isEmpty(stack):
postfixString += stackTop(stack)
stack.pop()
return postfixString
def main():
expression = "a+b*(c^d-e)^(f+g*h)-i"
postfix = ConvertToPostfix(expression)
print postfix # outout abcd^e-fgh*+^*+i-
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment