Created
June 24, 2020 09:23
-
-
Save LarryKarani/4a714f0f94f10e67e7a5596244bac278 to your computer and use it in GitHub Desktop.
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
#NB used python3 | |
#2 Create a simple calculator | |
def eval_helper(expression, index=0): | |
result=0 | |
op='+' | |
while index < len(expression): | |
char=expression[index] | |
if char.isdigit(): | |
if op == '+': | |
result += int(char) | |
else: | |
result -= int(char) | |
elif char in('+','-'): | |
op = char | |
elif char == '(': | |
n, index = eval_helper(expression, index + 1) | |
if op == '+': | |
result += n | |
else: | |
result -= n | |
elif char == ')': | |
return(result, index) | |
index += 1 | |
return(result, index) | |
def eval(expression): | |
return eval_helper(expression)[0] | |
#print (eval('-(3+(2-1))')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment