#!/usr/bin/env python3 # -*- coding: utf-8 -*- # file = "./ex.txt" file = "./input.txt" def max_length(li:list[str]) -> int: res = 0 for l in li: if len(l) > res: res = len(l) return res def expand_lines(li:list[str], nl:int) -> list[str]: res = [] for l in li: while len(l) < nl: l += "x" res.append(l) return res def get_numbers(li:list[str]) -> list[int]: res = [] part = [] num = "" for pos in range(len(li[0])): for l in li: if l[pos] != "x": num += l[pos] if num != "": part.append(int(num)) num = "" else: res.append(part) part = [] res.append(part) return res if __name__ == "__main__": solution = 0 lines = [] operator_list = [] input_file = open(file, "r") for line in input_file: line = line.replace(" ","x") line = line.strip() if line == "": continue elif "*" in line or "+" in line: operator_list = line.replace("x"," ").split() else: lines.append(line) lines = expand_lines(lines, max_length(lines)) num_list = get_numbers(lines) for i in range(len(operator_list)): if operator_list[i] == "+": op_result = 0 for n in num_list[i]: op_result += n elif operator_list[i] == "*": op_result = 1 for n in num_list[i]: op_result *= n else: op_result = None solution += op_result print(f"Solution: {solution}")