clearer variable names, added comments

bram-benchmarks
Brechtje van Gessel 2025-12-03 23:53:42 +01:00
parent 561edcc1a5
commit 94e87bdae1
1 changed files with 18 additions and 10 deletions

View File

@ -1,19 +1,27 @@
input = open("input.txt").read().splitlines()
def find_biggest_num(line, start, is_first_num):
num = -1
max_num = 9
# line = current line that is being searched
# start = at what index to start searching
# for the first digit: 0
# for the second digit: right after the index of the first digit
# is_first_digit = boolean, True if first digit is being found, False if second digit is being found
# num_to_find = (next) number to search for in the string (line), starts at 9 decreases when not found
def find_biggest_num_index(line, start, is_first_digit):
index = -1
num_to_find = 9
while True:
num = line.find(str(max_num), start)
if num == -1 or (is_first_num and num == len(line) - 1):
max_num -= 1
index = line.find(str(num_to_find), start)
# decrease num_to_find if number is not found
# OR we are currently searching for the first digit and the number found is the last char in the string
if index == -1 or (is_first_digit and index == len(line) - 1):
num_to_find -= 1
else:
return num
return index
answer = 0
for line in input:
first_num = find_biggest_num(line, 0, True)
second_num = find_biggest_num(line, first_num + 1, False)
answer += int(line[first_num] + line[second_num])
first_digit_index = find_biggest_num_index(line, 0, True)
second_digit_index = find_biggest_num_index(line, first_digit_index + 1, False)
answer += int(line[first_digit_index] + line[second_digit_index])
print(answer)