#advent of code 2024 #day 03 #could be improved to match only numbers of lengths 1-3 #instead of if statements in mul function import re def mul(foundmatch): foundmatch = foundmatch[4:-1]; v1, v2 = [int(val) for val in foundmatch.split(",")]; if v1 > 999: v1 = 0; if v2 > 999: v2 = 0; return v1*v2; part1 = 0; part2 = 0; instr = []; f = open("03.in","r") for line in f: regmatch = r'(mul\(\d+,\d+\))|(don\'t\(\))|(do\(\))'; for m in re.findall(regmatch,line): instr.append(m); f.close(); ok = True; for i in instr: m, dn, do = i; #mul() / dont() / do() if dn: ok = False; elif do: ok = True; if m: v = mul(m); part1 += v; part2 += v*ok; print("part 1 =", part1); print("part 2 = ", part2);