def evaluate(expression):
opp = '-'
acc = 0
for i,x in enumerate(expression.split()):
if i==0:#first number into accumulator
acc = int(x)
elif x=='*' or x=='+':
opp = x
elif opp == '+':
acc = acc + int(x)
elif opp == '*':
acc = acc * int(x)
else:
print ('not sure what happened')
# print (expression.split(), acc)
return (acc)
def p2Evaluate (expression):
split_exp = expression.split('*')
ret = 1
for multiple in split_exp:
ret = ret * evaluate(multiple)
return (ret)
def SplitBrackets(string):
"""Generate parenthesized contents in string as pairs (level, contents)."""
stack = []
for i, c in enumerate(string):
if c == '(':
stack.append(i)
elif c == ')' and stack:
start = stack.pop()
yield (len(stack), string[start + 1: i])
# start
input_file = open("18Input.txt", "r")
#data = [(line.strip()).split() for line in input_file]
data = [line.strip() for line in input_file]
input_file.close()
last_depth = 0
max_depth = 0
calced_subs = []
sub = []
grand_total = 0
for full_exp in data:
full_exp = '('+full_exp+')'
sb = SplitBrackets(full_exp)
for exp in sb:
print (exp)
sb = SplitBrackets(full_exp)
for index, exp in enumerate(sb):
depth = exp
if index == 0:
max_depth = depth
last_depth = max_depth
print (max_depth)
print ('---------------------------Expression ',exp)
if depth<last_depth:
string = exp [1]
print ('Presub ',string)
sub = calced_subs.pop()
print ('popped sub', sub)
while last_depth == sub[0]:
string = string.replace('('+sub[1]+')',sub[2])
print ('Postsub ',string)
if len (calced_subs)>0:
sub = calced_subs.pop()
print ('popped sub', sub)
else: break
calced_subs.append(sub) # - put last popped sub back
print ('about to evaluate ' , string)
this_sub = [exp[0],exp[1],str(p2Evaluate(string))]
print ('About to append ',this_sub)
calced_subs.append (this_sub)
if depth >= last_depth:
this_sub = [exp[0],exp[1],str(p2Evaluate(exp[1]))]
print ('About to append ',this_sub)
calced_subs.append (this_sub)
last_depth = depth
grand_total = grand_total + int(this_sub[2])
print (grand_total)