Let's see how far I get this year.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

day01-1.py 1.1KB

1234567891011121314151617181920212223242526272829303132333435
  1. def main():
  2. from string import digits
  3. with open("input01.txt", "r") as file:
  4. input_lines = file.readlines()
  5. # The calibration value of each line is the first and last digit
  6. # in each line, in order, combined to make a two-digit number.
  7. calibrations = []
  8. for line in input_lines:
  9. line = line.strip()
  10. if line == "":
  11. continue
  12. first = ""
  13. last = ""
  14. for i, char in enumerate(line):
  15. if char in digits:
  16. # print(f"Found first digit in {line} at position {i}: {char}")
  17. first = char
  18. break
  19. for i, char in enumerate(line[::-1]):
  20. if char in digits:
  21. # print(f"Found last digit in {line} at position {len(line) - i}: {char}")
  22. last = char
  23. break
  24. calibrations.append(int(first + last))
  25. print(calibrations)
  26. # The total calibration value is the sum of the individual
  27. # calibration values.
  28. print(f"Total calibration value: {sum(calibrations)}")
  29. if __name__ == "__main__":
  30. main()