Last active
August 29, 2015 14:03
-
-
Save kgleeson/8a8d1c74fe3208803ef5 to your computer and use it in GitHub Desktop.
Simple expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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