input = open("input.txt").read().splitlines() # 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: 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 index answer = 0 for line in input: 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)