Last active
December 18, 2020 22:12
-
-
Save sahibjotsaggu/bcb2718446f8082f761bfb1bf38a03ce 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
expr = inp.split('\n') | |
# PART 1 | |
# expr is a simple expression that has no parentheses | |
def evaluate(expr, part=1): | |
if part == 2: | |
if expr.find('(') > -1: | |
return [str(eval(expr))] | |
else: | |
expr = ' '.join(addParentsAroundAddition(expr.split(' '))) | |
return [str(eval(expr))] | |
expr = expr.replace('(','') | |
expr = expr.replace(')', '') | |
splitExpr = expr.split(' ') | |
while len(splitExpr) > 1: | |
partialResult = None | |
for x in range(len(splitExpr)): | |
if not splitExpr[x].isdigit(): | |
operand = splitExpr[x] | |
left = splitExpr[x - 1] | |
right = splitExpr[x + 1] | |
partialResult = eval(left + operand + right) | |
break | |
if partialResult: | |
splitExpr = [str(partialResult)] + splitExpr[3:] | |
return splitExpr | |
# Find the inner most parentheses | |
def innerParentheses(expr, part=1): | |
pIndex = [] | |
parentheses = [] | |
mostRecent = '' | |
hasParen = False | |
for x in expr: | |
if x == '(': | |
hasParen = True | |
break | |
if hasParen: | |
for x in range(len(expr)): | |
if expr[x] == '(': | |
if mostRecent != '(': | |
pIndex.append(x) | |
mostRecent = '(' | |
else: | |
pIndex = [x] | |
else: | |
if expr[x] == ')' and mostRecent == '(': | |
pIndex.append(x) | |
mostRecent = '' | |
if (len(pIndex) == 2): | |
parentheses.append(pIndex) | |
if part == 1: | |
expr = expr[:pIndex[0]] + evaluate(''.join(expr[pIndex[0] + 1:pIndex[1]])) + expr[pIndex[1] + 1:] | |
else: | |
expr = expr[:pIndex[0]] + evaluate(' '.join(addParentsAroundAddition(''.join(expr[pIndex[0] + 1:pIndex[1]]).split(' '))), 2) + expr[pIndex[1] + 1:] | |
return innerParentheses(expr, part) | |
pIndex = [] | |
return expr | |
res = 0 | |
for x in expr: | |
res += int(evaluate(''.join(innerParentheses(list(x))))[0]) | |
print(res) | |
# PART 2 | |
# Addition should be evaluated before multiplication | |
def getAdditionIndices(expr): | |
indices = [] | |
for x in range(len(expr)): | |
if expr[x] == '+': | |
indices.append(x) | |
return indices | |
def addParentsAroundAddition(expr): | |
additionIndices = getAdditionIndices(expr) | |
for x in range(len(expr)): | |
if x in additionIndices: | |
expr[x - 1] = '(' + expr[x - 1] | |
expr[x + 1] += ')' | |
return expr | |
res = 0 | |
for x in expr: | |
res += int(evaluate(''.join(innerParentheses(list(x), 2)), 2)[0]) | |
print(res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment