Advent of Code 2024 - Day 2

# Part 1

 1def get_data(path):
 2    with open(path) as f:
 3        for line in f:
 4            line = line.strip()
 5            yield [int(x) for x in line.split()]
 6
 7
 8def is_safe(report):
 9    is_decending = report[0] > report[1]
10
11    for i, j in zip(report[:-1], report[1:]):
12        if is_decending:
13            if not (1 <= i - j <= 3):
14                return False
15        else:
16            if not (1 <= j - i <= 3):
17                return False
18
19    return True
20
21def main(data):
22    safe_reports = 0
23    for report in data:
24        if is_safe(report):
25            safe_reports += 1
26    return safe_reports
27
28
29if __name__ == '__main__':
30    print(main(get_data("day_2_input.txt")))

# Part 2

 1def get_data():
 2    with open("day_2_input.txt") as f:
 3        for line in f:
 4            line = line.strip()
 5            yield [int(x) for x in line.split()]
 6
 7
 8def is_safe(report):
 9    is_decending = report[0] > report[1]
10
11    for i, j in zip(report[:-1], report[1:]):
12        if is_decending:
13            if not (1 <= i - j <= 3):
14                return False
15        else:
16            if not (1 <= j - i <= 3):
17                return False
18
19    return True
20
21def any_safe(report):
22    for i in range(len(report)):
23        new_report = report[:i] + report[i + 1:]
24        if is_safe(new_report):
25            return True
26    return False
27
28def main(data):
29    safe_reports = 0
30    for report in data:
31        if any_safe(report):
32            safe_reports += 1
33    return safe_reports
34
35
36if __name__ == '__main__':
37    print(main(get_data()))