Skip to content

Instantly share code, notes, and snippets.

@nava45
Created August 25, 2013 11:38
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 nava45/6333409 to your computer and use it in GitHub Desktop.
Save nava45/6333409 to your computer and use it in GitHub Desktop.
Infix expression Evaluation in Python
import operator
ops = {'+':operator.add,'-':operator.sub,'*':operator.mul,'/':operator.div}
class Stack:
def __init__(self):
self.mylist = []
def isempty(self):
return True if len(self.mylist) == 0 \
else False
def top(self):
if self.isempty():
print "Stack is Empty"
return 0
else:
return self.mylist[-1]
def push(self,item):
print "Pushing : %s" %item
self.mylist.append(item)
def pop(self):
if not self.isempty():
print "popping: %s" %self.top()
return self.mylist.pop()
else:
print "Stack is Empty"
return None
def do_infix_evaluation(items):
print "****Evaluating the preceding items****",items
items = map(lambda x: x if not isinstance(x,str) else int(x),items)
print items
firstitem = items.pop()
prevresult = firstitem
while firstitem:
try:
if hasattr(firstitem,'__call__'):
prevresult = firstitem(prevresult,items.pop())
firstitem = items.pop()
except IndexError:
return prevresult
print "****** Evaluated Result is : %s" %prevresult
return prevresult
def pop_until_openbrace(stack):
tlist = []
item = stack.pop()
eres = 0
while item != '(':
if item:
tlist.append(item)
item = stack.pop()
else:
print "Insufficient items in stack"
return
return do_infix_evaluation(tlist) if tlist else eres
def infix(expression):
print expression
stack = Stack()
for i in list(expression):
if i == ')':
stack.push(pop_until_openbrace(stack))
elif ops.has_key(i):
stack.push(ops[i])
else:
stack.push(i)
print "Result is :",stack.mylist
if __name__ == '__main__':
print "Enter expre:"
expr = raw_input()
infix(expr)
@hrieke
Copy link

hrieke commented Oct 20, 2023

Do you have a license for which this code is published under?
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment