from io import open import re import numpy as np from itertools import product #Hay algo mal y no sé qué es # We open the txt document containing the games input=open('input.txt','r') # We read the text inside distinguishing by lines text=input.readlines() # Close the txt file to be able to work on the text without having the file open. input.close() del(input) symbols=[] matches=[] list_text=[] #Eliminamos los números y los puntos para obtener los símbolos que hay numbers=[] for i in range(0,10): numbers.append(str(i)) for line in text: line=line.strip() for element in line: if element not in numbers and element!="." and element not in symbols: symbols.append(element) # Identificamos la posición en la que se encuentran los símbolos for position,line in enumerate(text): line=line.strip() list_text.append(re.split('',line)) del(list_text[position][0]) del(list_text[position][-1]) for symbol in symbols: try: #print(symbol,position,text[position].index(symbol)) find=position,list_text[position].index(symbol) matches.append(find) except ValueError: pass #Identificamos las posiciones alrededor del símbolo que tiene números y los guardamos en una variable que se llama position_numbers=[] position_numbers=[] for symbol in matches: row_option=symbol[0] column_option=symbol[1] extra_positions = len(str(symbol[0])) #iteramos las posiciones que están alrededor del símbolo mediante iteración posible_rows=list(range(max(0,row_option-1),min(row_option+2,len(text)))) #+2 porque el range no incluye el último número, len(text)=número filas máxima posible_columns=list(range(max(0,column_option-1),min(column_option+extra_positions+1,len(text)))) #Guardamos las posiciones de los números que rodean a los simbolos combinations_numbers=list(product(posible_rows,posible_columns)) for number in combinations_numbers: value=text[number[0]][number[1]] if value.isdigit(): position_numbers.append((number[0],number[1])) #Una vez tenemos los dígitos que rodean a los simbolos hay que ver si tienen números adyacentes a estos para agrupar los números visit_numbers=[] final_numbers=[] for row,column in position_numbers: first_col=column last_col=column if (row,column) not in visit_numbers: while text[row][first_col].isdigit() and first_col >= 0: visit_numbers.append((row, first_col)) first_col = first_col - 1 try: while text[row][last_col].isdigit() and last_col < len(text): visit_numbers.append((row, last_col)) last_col = last_col + 1 except: pass final_numbers.append(int(text[row][first_col+1:last_col])) print(sum(final_numbers))