aoc2025/bob/day06/day06-p2.py

79 lines
1.7 KiB
Python

def operate(operator,a,b):
if operator == "*":
return int(a) * int(b)
if operator == "+":
return int(a) + int(b)
return None
def calculate_column(col):
# Generate a list of correct numbers from the strings
numbers = []
for index in range(len(col[0])-1,-1,-1):
number = ""
for num in range(0, len(col)-1):
number += col[num][index:index+1]
numbers.append(number.strip())
# Loop numbers for calculation
res = int(numbers[0])
for num in range(1, len(numbers)):
res = operate(col[-1], res, numbers[num])
return res
def find_next_op(ops_string):
plus = ops_string[1:].find("+")
mul = ops_string[1:].find("*")
if plus == -1:
plus = len(ops_string) # if not found, set to end of string
if mul == -1:
mul = len(ops_string) # if not found, set to end of string
if plus < mul:
return plus
return mul
def read_input(filename):
lines = []
for line in open(filename).read().splitlines():
lines.append(line)
sheet = []
while True:
ops = lines[-1]
sep_length = find_next_op(ops)
nums = []
for line in range(0,len(lines)-1):
num = lines[line][0:sep_length]
lines[line] = lines[line][sep_length+1:]
nums.append(num)
lines[-1] = lines[-1][sep_length+1:]
nums.append(ops[0:1])
sheet.append(nums)
if len(lines[-1]) == 0:
break
return sheet
# filename = "day06/example_input" # 3263827
filename = "day06/input" # 9608327000261
sheet = read_input(filename)
total = 0
for col in sheet:
total += calculate_column(col)
print(f"Total of sheet operations: {total}")