-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaoc202002_class.py
87 lines (61 loc) · 2.26 KB
/
aoc202002_class.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""AoC 2, 2020: Password Philosophy."""
# Standard library imports
import pathlib
import sys
from dataclasses import dataclass
# Third party imports
import parse
PASSWORD_PATTERN = parse.compile("{first:d}-{second:d} {char}: {password}")
@dataclass
class PasswordPolicy:
first: int
second: int
char: str
password: str
@classmethod
def from_str(cls, line):
"""Parse one line into a PasswordPolicy.
>>> PasswordPolicy.from_str("4-6 e: adventofcode")
PasswordPolicy(first=4, second=6, char='e', password='adventofcode')
"""
return cls(**PASSWORD_PATTERN.parse(line).named)
def is_valid_count(self):
"""Check if the password follows the count requirements.
## Examples:
>>> PasswordPolicy.from_str("4-6 e: adventofcode").is_valid_count()
False
>>> PasswordPolicy.from_str("1-3 o: passwordphilosophy").is_valid_count()
True
"""
return self.first <= self.password.count(self.char) <= self.second
def is_valid_position(self):
"""Check if the password follows the position requirements.
## Examples:
>>> PasswordPolicy.from_str("4-6 e: adventofcode").is_valid_position()
True
>>> PasswordPolicy.from_str("1-3 o: passwordphilosophy").is_valid_position()
False
"""
return self._has_char(self.first) != self._has_char(self.second)
def _has_char(self, pos):
"""Check if password has the character in the given position."""
return self.password[pos - 1] == self.char
def parse_data(puzzle_input):
"""Parse input."""
return [PasswordPolicy.from_str(line) for line in puzzle_input.split("\n")]
def part1(data):
"""Solve part 1."""
return sum(policy.is_valid_count() for policy in data)
def part2(data):
"""Solve part 2."""
return sum(policy.is_valid_position() for policy in data)
def solve(puzzle_input):
"""Solve the puzzle for the given input."""
data = parse_data(puzzle_input)
yield part1(data)
yield part2(data)
if __name__ == "__main__":
for path in sys.argv[1:]:
print(f"\n{path}:")
solutions = solve(puzzle_input=pathlib.Path(path).read_text().strip())
print("\n".join(str(solution) for solution in solutions))