Last active
April 18, 2016 17:34
-
-
Save KarthikMAM/db3ae444eab744047606650a7a791202 to your computer and use it in GitHub Desktop.
An algorithm to evaluate mathematical expressions by partial postfix conversion optimization
This file contains 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
#precedance and the operation of each binary operator | |
prec = { "**": 3, | |
"*": 2, | |
"/": 2, | |
'%': 2, | |
"+": 1, | |
"-": 1, | |
"$": 0} | |
operFunc = {'+': lambda a, b: a + b, | |
'-': lambda a, b: a - b, | |
'*': lambda a, b: a * b, | |
'/': lambda a, b: a / b, | |
'%': lambda a, b: a % b, | |
"**": lambda a, b: a ** b} | |
#Get the user input | |
operator, operand = [], [] | |
expr = input() + " $" | |
for i in expr.split(" "): | |
#print(operand, operator, i) | |
if i.isdigit(): | |
#Push all the operands into the stack | |
operand.append(int(i)) | |
else: | |
#While the precedance of the top of stack | |
#is equal to or less than new operator | |
#perform the opration of operator on top of the stack | |
#and then push the new operator | |
while len(operator) > 0 and prec[i] <= prec[operator[len(operator) - 1]]: | |
#print(operand, operator) | |
opr = operator.pop() | |
op1 = operand.pop() | |
op2 = operand.pop() | |
operand.append(func[opr](op2, op1)) | |
operator.append(i) | |
print(operand[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple python program to evaluate an infix expression by converting it to a post fix expression