from io import open import re import numpy as np from itertools import product # We open the txt document containing the games input=open('input.txt','r') # We read the text inside distinguishing by lines lines = input.readlines() # Close the txt file to be able to work on the text without having the file open. input.close() del(input) for i in range(len(lines)): lines[i] = lines[i].replace("\n", "") list_symbols = [] cont_row = 0 for line in lines: cont_col = 0 for letter in line: if letter != '.' and not letter.isdigit(): list_symbols.append((letter, cont_row, cont_col)) cont_col += 1 cont_row += 1 pos_numbers = [] for option in list_symbols: row_option = option[1] col_option = option[2] extra_positions = len(str(option[0])) possible_rows = list(range(max(0, row_option-1), min(row_option+2, len(lines)))) possible_columns = list(range(max(0, col_option-1), min(col_option+extra_positions+1, len(lines[0])))) combinations = list(product(possible_rows, possible_columns)) checked = False for combination in combinations: value = lines[combination[0]][combination[1]] if value.isdigit(): pos_numbers.append((combination[0], combination[1])) checked = True visited_numbers = [] final_numbers = [] for row, col in pos_numbers: first_col = col last_col = col if (row, col) not in visited_numbers: while lines[row][first_col].isdigit() and first_col >= 0: visited_numbers.append((row, first_col)) first_col = first_col - 1 try: while lines[row][last_col].isdigit() and last_col < 140: visited_numbers.append((row, last_col)) last_col = last_col + 1 # print(last_col) except: pass final_numbers.append(int(lines[row][first_col+1:last_col])) print(sum(final_numbers))