|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- from helpers import Helper
-
- helper = Helper(debug=True)
- debug = helper.debug
- load_input = helper.load_input
-
- def main():
- from string import digits
-
- DIGITS_SPELLED = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
-
- input_lines = load_input(1)
-
- # The calibration value of each line is the first and last digit
- # in each line, in order, combined to make a two-digit number.
- calibrations = []
- for line in input_lines:
- line = line.strip()
- if line == "":
- continue
- first = ""
- last = ""
- spelled_digits = {}
- first_spelled = len(line) + 1
- last_spelled = -1
- for digit in DIGITS_SPELLED:
- position = 0
- while position < len(line):
- debug(f"{position=}", end=" ")
- if digit in line[position:]:
- new_index = line[position:].index(digit)
- spelled_digits[new_index + position] = str(DIGITS_SPELLED.index(digit))
- position += new_index + 1
- else:
- position = len(line)
- if len(spelled_digits) > 0:
- first_spelled = min(spelled_digits.keys())
- last_spelled = max(spelled_digits.keys())
- debug(spelled_digits, first_spelled, last_spelled)
- for i, char in enumerate(line):
- if char in digits:
- if i < first_spelled:
- debug(f"Found first digit in {line} at position {i}: {char}")
- first = char
- break
- else:
- debug(f"Found first digit in {line} at position {first_spelled}: {spelled_digits[first_spelled]}")
- first = spelled_digits[first_spelled]
- break
- for i, char in enumerate(line[::-1]):
- if char in digits:
- if (len(line) - i) > last_spelled:
- debug(f"Found last digit in {line} at position {len(line) - i}: {char}")
- last = char
- break
- else:
- debug(f"Found last digit in {line} at position {last_spelled}: {spelled_digits[last_spelled]}")
- last = spelled_digits[last_spelled]
- break
- calibrations.append(int(first + last))
-
- debug(calibrations)
-
- # The total calibration value is the sum of the individual
- # calibration values.
- print(f"Total calibration value: {sum(calibrations)}")
-
- if __name__ == "__main__":
- main()
|