Skip to content

Instantly share code, notes, and snippets.

@evanlimanto
Created November 14, 2017 00:58
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 evanlimanto/7018ea542d77bd1d74069ee1b30c3a6e to your computer and use it in GitHub Desktop.
Save evanlimanto/7018ea542d77bd1d74069ee1b30c3a6e to your computer and use it in GitHub Desktop.
def is_number(character):
return character.isdigit()
def is_operator(character):
return character == '+' or character == '*'
def handle_operation(operand_one, operator, operand_two):
if operator == '+':
return operand_one + operand_two
elif operator == '*':
return operand_one * operand_two
raise ValueError('Invalid operator: {}'.format(operator))
def handle_number(stack, number):
if len(stack) == 0:
stack.append(number)
return
if stack[-1] == '(':
# Remove opening parenthesis
stack.pop()
stack.append(number)
return
# Top of stack is an operator
operator = stack[-1]
operand = stack[-2]
result = handle_operation(operand, operator, number)
# Pop first two elements and push result into stack
stack.pop()
stack.pop()
stack.append(result)
def handle_closing_paren(stack):
operand = stack.pop()
# Pop first two elements off stack
handle_number(stack, operand)
def parse_expression(expr):
stack = []
for i in range(len(expr)):
character = expr[i]
if character == '(':
stack.append(character)
elif character == ')':
handle_closing_paren(stack)
elif is_number(character):
handle_number(stack, int(character))
elif is_operator(character):
stack.append(character)
return stack[0]
if __name__ == '__main__':
print(parse_expression('((1+2)*3)'))
print(parse_expression('(1+(2*3))'))
print(parse_expression('(2+3)'))
print(parse_expression('((1+((2+3)*4))+5)'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment