|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- DEBUG = False
- DEBUG_PREFIX = ""
-
- def debug(message, *args, **kwargs):
- if DEBUG:
- print(f"{DEBUG_PREFIX} {message}", *args, **kwargs)
-
- def main():
- from string import digits
-
- DIGITS_SPELLED = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
-
- with open("day01.input", "r") as file:
- input_lines = file.readlines()
-
- # 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()
|