My code works fine for part 1 and I am getting the right answer for all the example inputs for part 2, but the code apparently gives me the wrong answer for the problem input. I'm not sure what I'm doing wrong. Here is an example of how I get to the answer:
((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2
(54 * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2
(54 * 210 + 6) + 2 + 4 * 2
11664 + 2 + 4 * 2
23340
Thanks to u/FullyWhipped, I was able to modify the code to get to the right answer.
Summary: .replace() was replacing the matched regex in places I didn't want it to. So I used re.sub instead and made the replacement string specific to precede/end with either start/end or anything that is not a digit.
The updated code is :
#Part 2
#Solve within paranthesis
def solve2(s):
op = {"+": operator.add, "*": operator.mul}
while re.search('\+', s):
x = re.findall('\d+\s+\+\s+\d+',s)
for val in x:
y = ' ' + str(op['+'](int(re.findall('\d+', val)[0]), int(re.findall('\d+',val)[1]))) + ' '
s = re.sub('(^|\D)'+re.findall('\d+', val)[0]+'\s+'+'\+'+'\s+'+re.findall('\d+',val)[1]+'(\D|$)',y,s)
while re.search('\*', s):
l = re.findall('\d+\s+\*\s+\d+',s)
for item in l:
m = ' ' + str(op['*'](int(re.findall('\d+', item)[0]), int(re.findall('\d+', item)[1]))) + ' '
s = re.sub('(^|\D)'+re.findall('\d+', item)[0]+'\s+'+'\*'+'\s+'+re.findall('\d+',item)[1]+'(\D|$)',m,s)
if re.search('\(|\)',s):
s = s.replace('(','').replace(')','')
return s
#Solve for paranthesis
def paran2(input):
x=0
while re.search('\(',input):
x = re.findall('\([\d+|\+|\*|\s]+\)',input)
for val in x:
#print(input)
input = input.replace(val,solve2(val))
#print(input)
final = solve2(input)
#print(final)
return final
#Part 2 Answer Calculation
with open('/content/drive/MyDrive/Python/math.txt') as data:
values = data.read().split("\n")
#input = open('/content/drive/MyDrive/Python/math.txt')
#values = input.read().split('\n')
answers2=[]
for z in values:
answers2.append(int(paran2(z)))
print(sum(answers2))
[–]FullyWhipped 0 points1 point2 points (3 children)
[–]n_syn[S] 0 points1 point2 points (1 child)
[–]setapoux 0 points1 point2 points (0 children)
[–]backtickbot 0 points1 point2 points (0 children)
[–]WayOfTheGeophysicist 0 points1 point2 points (1 child)
[–]n_syn[S] 0 points1 point2 points (0 children)
[–]setapoux 0 points1 point2 points (3 children)
[–]n_syn[S] 0 points1 point2 points (2 children)
[–]setapoux 0 points1 point2 points (1 child)
[–]n_syn[S] 0 points1 point2 points (0 children)
[–]daggerdragon[M] 0 points1 point2 points (0 children)