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.

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