02_solution.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Dec 2 18:25:45 2024
  5. @author: bernie
  6. """
  7. def solve_part_1(inpt):
  8. diff_lines = [[int(nr1) - int(nr2) for nr1, nr2 in zip(line, line[1:])] for line in inpt]
  9. no_safe_reports = sum(
  10. all(nr >= 1 and nr <= 3 for nr in line) or
  11. all(nr <= -1 and nr >= -3 for nr in line)
  12. for line in diff_lines)
  13. print(f"safe reports (part 1): {no_safe_reports}")
  14. def _is_report_safe(line):
  15. all_in_range = all(nr1 != nr2 and abs(nr1 - nr2) <= 3 for nr1, nr2 in zip(line, line[1:]))
  16. all_increasing = all(nr1 > nr2 for nr1, nr2 in zip(line, line[1:]))
  17. all_decreasing = all(nr1 < nr2 for nr1, nr2 in zip(line, line[1:]))
  18. return all_in_range and (all_increasing or all_decreasing)
  19. def solve_part_2(inpt):
  20. inpt = [[int(nr) for nr in line] for line in inpt]
  21. no_safe_reports = 0
  22. for line in inpt:
  23. if _is_report_safe(line):
  24. no_safe_reports += 1
  25. continue
  26. for idx_to_rm in range(len(line)):
  27. modified_line = line[:idx_to_rm] + line[idx_to_rm+1:]
  28. if _is_report_safe(modified_line):
  29. no_safe_reports += 1
  30. break
  31. print(f"safe reports (part 2): {no_safe_reports}")
  32. if __name__ == "__main__":
  33. with open("02_input.txt", "r") as inpt_file:
  34. inpt = [line.split(" ") for line in inpt_file.readlines()]
  35. solve_part_1(inpt)
  36. solve_part_2(inpt)