Created
December 2, 2024 21:08
-
-
Save rodrigogiraoserrao/91be0a545ab0506b1cc69ab7ef73d16f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # === Parsing === | |
| reports = [] | |
| with open("input.txt", "r") as f: | |
| reports = [ | |
| [int(num) for num in line.split()] | |
| for line in f | |
| ] | |
| print(reports) | |
| # === Part 1 === | |
| from itertools import pairwise | |
| safe = 0 | |
| for report in reports: | |
| direction = 0 # Positive means up, negative means down | |
| for left, right in pairwise(report): | |
| if not 1 <= abs(left - right) <= 3: | |
| break | |
| if direction * (right - left) < 0: | |
| break | |
| direction = right - left | |
| else: | |
| safe += 1 | |
| print(safe) | |
| # === Part 2 === | |
| from itertools import pairwise | |
| def is_safe(report, direction): | |
| for left, right in pairwise(report): | |
| if not 1 <= abs(left - right) <= 3: | |
| return False | |
| if direction * (right - left) < 0: | |
| return False | |
| return True | |
| safe = 0 | |
| for report in reports: | |
| this_safe = is_safe(report, report[1] - report[0]) | |
| idx = 0 | |
| while not this_safe and idx < len(report): | |
| smaller_report = report[:idx] + report[idx + 1 :] | |
| this_safe = is_safe( | |
| smaller_report, | |
| smaller_report[1] - smaller_report[0], | |
| ) | |
| idx += 1 | |
| safe += this_safe | |
| print(safe) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment