Let's see how far I get this year.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

day01-2.py 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. DEBUG = False
  2. DEBUG_PREFIX = ""
  3. def debug(message, *args, **kwargs):
  4. if DEBUG:
  5. print(f"{DEBUG_PREFIX} {message}", *args, **kwargs)
  6. def main():
  7. from string import digits
  8. DIGITS_SPELLED = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
  9. with open("input01.txt", "r") as file:
  10. input_lines = file.readlines()
  11. # The calibration value of each line is the first and last digit
  12. # in each line, in order, combined to make a two-digit number.
  13. calibrations = []
  14. for line in input_lines:
  15. line = line.strip()
  16. if line == "":
  17. continue
  18. first = ""
  19. last = ""
  20. spelled_digits = {}
  21. first_spelled = len(line) + 1
  22. last_spelled = -1
  23. for digit in DIGITS_SPELLED:
  24. position = 0
  25. while position < len(line):
  26. debug(f"{position=}", end=" ")
  27. if digit in line[position:]:
  28. new_index = line[position:].index(digit)
  29. spelled_digits[new_index + position] = str(DIGITS_SPELLED.index(digit))
  30. position += new_index + 1
  31. else:
  32. position = len(line)
  33. if len(spelled_digits) > 0:
  34. first_spelled = min(spelled_digits.keys())
  35. last_spelled = max(spelled_digits.keys())
  36. debug(spelled_digits, first_spelled, last_spelled)
  37. for i, char in enumerate(line):
  38. if char in digits:
  39. if i < first_spelled:
  40. debug(f"Found first digit in {line} at position {i}: {char}")
  41. first = char
  42. break
  43. else:
  44. debug(f"Found first digit in {line} at position {first_spelled}: {spelled_digits[first_spelled]}")
  45. first = spelled_digits[first_spelled]
  46. break
  47. for i, char in enumerate(line[::-1]):
  48. if char in digits:
  49. if (len(line) - i) > last_spelled:
  50. debug(f"Found last digit in {line} at position {len(line) - i}: {char}")
  51. last = char
  52. break
  53. else:
  54. debug(f"Found last digit in {line} at position {last_spelled}: {spelled_digits[last_spelled]}")
  55. last = spelled_digits[last_spelled]
  56. break
  57. calibrations.append(int(first + last))
  58. debug(calibrations)
  59. # The total calibration value is the sum of the individual
  60. # calibration values.
  61. print(f"Total calibration value: {sum(calibrations)}")
  62. if __name__ == "__main__":
  63. main()