I am trying to implement a simple expression evaluator in python,but I am stuck in parser method.Below is my code snippet.
class Number:
def __init__(self,value):
self.value=value
def execute(self):
return self.value
class Plus:
def __init__(self,left,right):
self.left=left
self.right=right
def execute(self):
return self.left+self.right
class Minus:
def __init__(self,left,right):
self.left=left
self.right=right
def execute(self):
return self.left-self.right
class Multiply:
def __init__(self,left,right):
self.left=left
self.right=right
def execute(self):
return self.left*self.right
import re
def parser(input):
stack=[]
token_pat = re.compile("\s*(?:(\d+)|(.))")
for number, operator in token_pat.findall(input):
if number:
stack.append(Number(int(number)))
else:
first,second=stack.pop(),stack.pop()
if operator=="+":
stack.append(Plus(first,second))
elif operator=="-":
stack.append(Minus(first,second))
elif operator=="*":
stack.append(Multiply(first,second))
else:
raise SyntaxError("unknown operator")
print stack[0].execute()
if __name__=="__main__":
parser('1 2 +')
When I am running the above code,I am getting following error.Can anybody review my code .
Traceback (most recent call last):
File "Interpreter.py", line 52, in <module>
parser('1 2 +')
File "Interpreter.py", line 48, in parser
print stack[0].execute()
File "Interpreter.py", line 12, in execute
return self.left+self.right
TypeError: unsupported operand type(s) for +: 'instance' and 'in
The error message is that confusing because you’re using classic classes. With new-style classes (i.e. inheriting from
object), you get a much more reasonable:Either use
ints instead of Number objects, or implement adding logic by implementing__add__and friends, or add evaluating logic inPlus.execute.Also note that you’re reimplementing Python’s built-ins. Additionally, having an
executemethod is pretty much an anti-pattern. A much shorter implementation would be