Skip to content

Instantly share code, notes, and snippets.

@PeterStayPool
Created April 20, 2019 07:12
Given arithmetic equation, 2+(3-1)*4/(5-6), write the program to calculate the result of the equation.
class ComputeExpression:
def is_number(self, number):
return number.isdigit()
def is_op(self, oprand):
return oprand == '+' or oprand == '-' or oprand == '/' or oprand =='*' or oprand == ')' or oprand == '('
def is_left_parenthesis(self, oprand):
return oprand == '('
def is_plus_minus(self, oprand):
return oprand == '+' or oprand == '-'
def is_multiple_or_divide(self, oprand):
return oprand == '/' or oprand == '*'
def parse(self, expression):
self.op = []
self.numbers = []
pos = len(expression) -1
number = ''
while pos >= 0:
next = expression[pos]
if self.is_number(next) is True:
number = next + number
elif self.is_op(next) is True:
if len(number) > 0:
self.numbers.append(int(number))
number = ''
self.handle_op(next)
pos -= 1
if len(number) > 0 :
self.numbers.append(int(number))
while(len(self.op) > 0):
next_op = self.op.pop()
lvalue = self.numbers.pop()
rvalue = self.numbers.pop()
result = self.compute(next_op, lvalue, rvalue)
self.numbers.append(result)
return self.numbers[0]
def handle_op(self, cur_op):
if self.is_left_parenthesis(cur_op) is True:
self.compute_in_parenthesis()
return
if self.is_plus_minus(cur_op) is True and len(self.op) > 0 and self.is_multiple_or_divide(self.op[-1]) is True:
#compute previous plus and minue ops first before adding current multiple/divide op
while len(self.op) > 0:
cur = self.op[-1]
if self.is_multiple_or_divide(cur) != True:
break
lvalue = self.numbers.pop()
rvalue = self.numbers.pop()
result = self.compute(cur, lvalue, rvalue)
self.numbers.append(result)
self.op.pop()
self.op.append(cur_op)
def compute_in_parenthesis(self):
#compute all ops until right ')'
while len(self.op) > 0:
cur = self.op[-1]
if cur == ')':
self.op.pop()
break
lvalue = self.numbers.pop()
rvalue = self.numbers.pop()
result = self.compute(cur, lvalue, rvalue)
self.numbers.append(result)
self.op.pop()
def compute(self, oprand, lvalue, rvalue):
if (oprand == '+'):
return lvalue + rvalue
elif (oprand == '-'):
return lvalue - rvalue
elif (oprand == '*'):
return lvalue * rvalue
elif (oprand == '/'):
return lvalue / rvalue
return None
c = ComputeExpression()
expr ="2+(3-1)*4/(5-6)"
print("%s = %d" % (expr, c.parse(expr)))
expr ="24+3*14-2"
print("%s = %d" % (expr, c.parse(expr)))
expr ="2+(3-1*1-2)*4/(5-6)"
print("%s = %d" % (expr, c.parse(expr)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment