Untitled

mail@pastecode.io avatar
unknown
python
7 months ago
2.1 kB
2
Indexable
Never
# day 1


def read_input(input_data_file: str) -> list[str]:
    with open(input_data_file, 'r', encoding='utf-8') as file:
        return file.readlines()


def find_left_number(row: str) -> int:
    for char in row:
        if char.isnumeric():
            return char
 
def find_right_number(row: str) -> int:
    for i in range(len(row)-1,-1,-1):
        if row[i].isnumeric():
            return row[i]        
    
    
def join_two_digits(n1, n2) -> str:
    return int(str(n1)+str(n2))

# cercare da sx a dx in ogni riga se esiste una chiave del dict che rappresenta i numeri

def find_spelled_nums(row: str) -> list[int]:
    numbers_spelled = {
        'one': 1,
        'two': 2, 
        'three': 3, 
        'four': 4, 
        'five': 5,
        'six': 6, 
        'seven': 7, 
        'eight': 8,
        'nine': 9
    }
    # lista contenente i due numeri estratti
    result = []
    # scorri la riga row e cerca la ricorrenza delle chiavi
    pattern = ''
    for char in row:
        #verifica prima se a sx c'è un numero
        if char.isnumeric():
            result.append(int(char))
            # print(f"trovato numero {char}")
        else:
            # costruisci il pattern 
            pattern += char
            # verifica se il pattern contiene una delle chiavi del dict
            for key in numbers_spelled.keys():
                if pattern.find(key) != -1:
                    # print(f"key {key} trovato in posizione {pattern.find(key)} nel pattern {pattern} ")
                    pattern = ''    
                    result.append(numbers_spelled[key])
    print(result)
    return result[0], result[-1]
    
strings_rows = read_input("aoc_sample.txt")
two_digits_list = []


for row in strings_rows:
    # n1 = find_left_number(row)
    # n2 = find_right_number(row)
    n1, n2 = find_spelled_nums(row)
    # print(n1, n2)
    two_digits_n = join_two_digits(n1, n2)
    two_digits_list.append(two_digits_n)

print(two_digits_list)
result = sum(two_digits_list)
print(result)
Leave a Comment