Skip to content

Instantly share code, notes, and snippets.

@kgleeson
Last active August 29, 2015 14:03
Show Gist options
  • Save kgleeson/8a8d1c74fe3208803ef5 to your computer and use it in GitHub Desktop.
Save kgleeson/8a8d1c74fe3208803ef5 to your computer and use it in GitHub Desktop.
Simple expression
Write a simple parser to parse a formula and calculate the result. Given a string containing only integer numbers, brackets, plus and minus signs, calculate and print the numeric answer. Assume that the formula will always follow correct syntax
Example input:
(2+2)-(3-(6-5))-4
Example output:
-2
def compute_expression(expr):
# Write your code here
# To print results to the standard output you can use print
# Example: print "Hello world!"
offset = 0
while ')' in expr:
close_bracket = expr.find(')')
open_bracket = expr.rfind('(', 0, close_bracket-1)
expr = expr[:open_bracket].strip('(') + do_math(expr[open_bracket:close_bracket]) + expr[close_bracket+1:]
print do_math(expr)
def do_math(expr):
return str(eval(expr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment