import re def check_symbols(line, idx_start, idx_end, previous, next): pattern = re.compile(r'[^a-zA-Z0-9.]') end_next_idx = idx_end + 2 start_prev_idx = idx_start - 1 if idx_end != len(line): end_next_idx = -1 if idx_start == 0: start_prev_idx = 0 if next: check_next = pattern.findall(next[start_prev_idx: end_next_idx]) else: check_next = [] if previous: check_previous = pattern.findall(previous[start_prev_idx: end_next_idx]) else: check_previous = [] check_left = pattern.findall(line[start_prev_idx]) check_right = pattern.findall(line[end_next_idx]) if check_next or check_previous or check_left or check_right: return True return False def get_digit(line): digit_pattern = re.compile(r'\d+') matches = digit_pattern.finditer(line) digits = [] for match in matches: start = match.start() end = match.end() - 1 digit = match.group() digits.append({'digit': digit, 'start_idx': start, 'end_idx': end}) return digits def play(filename): with open(filename) as file: total = 0 lines = file.read().splitlines() for i in range(len(lines)): current_line = lines[i] if i == 0: line_previous = '' else: line_previous = lines[i - 1] if i == len(lines) - 1: line_next = '' else: line_next = lines[i + 1] digits = get_digit(current_line) if digits: for digit in digits: is_engine = check_symbols(current_line, digit['start_idx'], digit['end_idx'], line_previous, line_next) if is_engine: total += int(digit['digit']) return total