-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathaoc202002_state-machine-parsing.py
108 lines (78 loc) · 2.73 KB
/
aoc202002_state-machine-parsing.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
"""AoC 2, 2020: Password Philosophy."""
# Standard library imports
import pathlib
import string
import sys
def parse_data(puzzle_input):
"""Parse input."""
return [parse_policy(line) for line in puzzle_input.split("\n")]
def parse_policy(line):
"""Parse one line into a password policy.
Use a hand-coded state machine for parsing:
https://dev.to/meseta/advent-of-code-day-02-a-59m0
>>> parse_policy("4-6 e: adventofcode")
{'first': 4, 'second': 6, 'char': 'e', 'password': 'adventofcode'}
"""
state = "first"
accumulator = ""
policy = {}
for char in line:
if state == "first":
if char.isdigit():
accumulator += char
else:
policy["first"] = int(accumulator)
accumulator = ""
state = "second"
continue
if state == "second":
if char.isdigit():
accumulator += char
else:
policy["second"] = int(accumulator)
accumulator = ""
state = "char"
continue
if state == "char":
policy["char"] = char
state = "password"
continue
if state == "password":
if char in string.ascii_lowercase:
accumulator += char
policy["password"] = accumulator
return policy
def part1(data):
"""Solve part 1."""
return sum(is_valid_count(**policy) for policy in data)
def part2(data):
"""Solve part 2."""
return sum(is_valid_position(**policy) for policy in data)
def is_valid_count(first, second, char, password):
"""Check if the password follows the count requirements.
## Examples:
>>> is_valid_count(first=4, second=6, char="e", password="adventofcode")
False
>>> is_valid_count(first=1, second=3, char="o", password="passwordphilosophy")
True
"""
return first <= password.count(char) <= second
def is_valid_position(first, second, char, password):
"""Check if the password follows the position requirements.
## Examples:
>>> is_valid_position(first=4, second=6, char="e", password="adventofcode")
True
>>> is_valid_position(first=1, second=3, char="o", password="passwordphilosophy")
False
"""
return (password[first - 1] == char) != (password[second - 1] == char)
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))