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() input = open("input.txt").read().splitlines()
def find_biggest_num(line, start, is_first_num): # line = current line that is being searched
num = -1 # start = at what index to start searching
max_num = 9 # 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: while True:
num = line.find(str(max_num), start) index = line.find(str(num_to_find), start)
if num == -1 or (is_first_num and num == len(line) - 1): # decrease num_to_find if number is not found
max_num -= 1 # 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: else:
return num return index
answer = 0 answer = 0
for line in input: for line in input:
first_num = find_biggest_num(line, 0, True) first_digit_index = find_biggest_num_index(line, 0, True)
second_num = find_biggest_num(line, first_num + 1, False) second_digit_index = find_biggest_num_index(line, first_digit_index + 1, False)
answer += int(line[first_num] + line[second_num]) answer += int(line[first_digit_index] + line[second_digit_index])
print(answer) print(answer)