Created
September 15, 2018 17:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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