-
Notifications
You must be signed in to change notification settings - Fork 0
/
part_a.py
executable file
·230 lines (195 loc) · 7.36 KB
/
part_a.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#!/usr/bin/env python3
from dataclasses import dataclass
from typing import List, Tuple
import utils
class Challenge(utils.BaseChallenge):
def solve(self, _input, debug=False):
"""
>>> Challenge().default_solve()
15922
"""
return Node.from_node_text(_input.strip()).get_score()
class Node:
garbage_class = NotImplemented
group_class = NotImplemented
@classmethod
def from_node_text(cls, node_text):
"""
>>> Group.from_node_text('{}')
Group([])
>>> Group.from_node_text('{{{}}}')
Group([Group([Group([])])])
>>> Group.from_node_text('{{},{}}')
Group([Group([]), Group([])])
>>> Group.from_node_text('{{{},{},{{}}}}')
Group([Group([Group([]), Group([]), Group([Group([])])])])
>>> Group.from_node_text('{<{},{},{{}}>}')
Group([Garbage('{},{},{{}}')])
>>> Group.from_node_text('{<a>,<a>,<a>,<a>}')
Group([Garbage('a'), Garbage('a'), Garbage('a'), Garbage('a')])
>>> Group.from_node_text('{{<a>},{<a>},{<a>},{<a>}}')
Group([Group([Garbage('a')]), Group([Garbage('a')]),
Group([Garbage('a')]), Group([Garbage('a')])])
>>> Group.from_node_text('{{<!>},{<!>},{<!>},{<a>}}')
Group([Group([Garbage('!>},{<!>},{<!>},{<a')])])
>>> Group.from_node_text('{{<!>},{<!>},{<!>},{<a>}}asdsdasd')
Traceback (most recent call last):
...
Exception: ...
>>> Group.from_node_text('{{<!>},{<!>},{<!>},{<a>}}{}')
Traceback (most recent call last):
...
Exception: ...
"""
group, remaining = cls.group_class.parse(node_text)
if remaining:
raise Exception(
f"Got extra text after end of group: "
f"'{remaining[:10]}{'...' if len(remaining) > 10 else ''}'")
return group
@classmethod
def parse(cls, text: str) -> Tuple['Node', str]:
raise NotImplementedError()
def get_score(self, parent_score=0):
raise NotImplementedError()
@dataclass
class Garbage(Node):
contents: str
START = '<'
END = '>'
ESCAPE = '!'
@classmethod
def parse(cls, text: str) -> Tuple['Node', str]:
"""
>>> Garbage.parse('<>')
(Garbage(''), '')
>>> Garbage.parse('<random characters>')
(Garbage('random characters'), '')
>>> Garbage.parse('<<<<>')
(Garbage('<<<'), '')
>>> Garbage.parse('<{!>}>')
(Garbage('{!>}'), '')
>>> Garbage.parse('<!!>')
(Garbage('!!'), '')
>>> Garbage.parse('<!!!>>')
(Garbage('!!!>'), '')
>>> Garbage.parse('<{o"i!a,<{i<a>')
(Garbage('{o"i!a,<{i<a'), '')
>>> Garbage.parse('<{o"i!a,<{i<a><sfdadsfds>')
(Garbage('{o"i!a,<{i<a'), '<sfdadsfds>')
"""
if text[:1] != cls.START:
raise Exception(
f"Was asked to parse garbage but didn't start with "
f"'{cls.START}': "
f"'{text[:10]}{'...' if len(text) > 10 else ''}'")
remaining = text[1:]
while remaining[:1] != cls.END:
if not remaining:
raise Exception(
f"Premature EOF: "
f"'{'...' if len(text) > 10 else ''}{text[-10:]}'")
if remaining[0] == cls.ESCAPE:
if len(remaining) < 2:
raise Exception(
f"Premature EOF: "
f"'{'...' if len(text) > 10 else ''}{text[-10:]}'")
remaining = remaining[2:]
continue
remaining = remaining[1:]
remaining = remaining[1:]
return cls(text[1:-(len(remaining) + 1)]), remaining
def __repr__(self):
return f"{type(self).__name__}({repr(self.contents)})"
def get_score(self, parent_score=0):
return 0
Node.garbage_class = Garbage
@dataclass
class Group(Node):
contents: List[Node]
START = '{'
END = '}'
DELIMITER = ','
@classmethod
def parse(cls, text: str) -> Tuple['Node', str]:
"""
>>> Group.parse('{}')
(Group([]), '')
>>> Group.parse('{{{}}}')
(Group([Group([Group([])])]), '')
>>> Group.parse('{{},{}}')
(Group([Group([]), Group([])]), '')
>>> Group.parse('{{{},{},{{}}}}')
(Group([Group([Group([]), Group([]), Group([Group([])])])]), '')
>>> Group.parse('{<{},{},{{}}>}')
(Group([Garbage('{},{},{{}}')]), '')
>>> Group.parse('{<a>,<a>,<a>,<a>}')
(Group([Garbage('a'), Garbage('a'), Garbage('a'), Garbage('a')]), '')
>>> Group.parse('{{<a>},{<a>},{<a>},{<a>}}')
(Group([Group([Garbage('a')]), Group([Garbage('a')]),
Group([Garbage('a')]), Group([Garbage('a')])]), '')
>>> Group.parse('{{<!>},{<!>},{<!>},{<a>}}')
(Group([Group([Garbage('!>},{<!>},{<!>},{<a')])]), '')
>>> Group.parse('{{<!>},{<!>},{<!>},{<a>}}asdsdasd')
(Group([Group([Garbage('!>},{<!>},{<!>},{<a')])]), 'asdsdasd')
"""
if text[:1] != cls.START:
raise Exception(
f"Was asked to parse group but didn't start with "
f"'{cls.START}': "
f"'{text[:10]}{'...' if len(text) > 10 else ''}'")
remaining = text[1:]
contents = []
while remaining[:1] != cls.END:
if not remaining:
raise Exception(
f"Premature EOF: "
f"'{'...' if len(text) > 10 else ''}{text[-10:]}'")
if contents:
if remaining[0] != cls.DELIMITER:
raise Exception(
f"Expected '{cls.DELIMITER}' between contents but got "
f"'{remaining[0]}'")
remaining = remaining[1:]
if not remaining:
raise Exception(
f"Premature EOF: "
f"'{'...' if len(text) > 10 else ''}{text[-10:]}'")
if remaining[0] == cls.START:
content, remaining = cls.parse(remaining)
contents.append(content)
elif remaining[0] == cls.garbage_class.START:
content, remaining = cls.garbage_class.parse(remaining)
contents.append(content)
else:
raise Exception(
f"Expected a group or a garbage, but got '{remaining[0]}'")
remaining = remaining[1:]
return cls(contents), remaining
def __repr__(self):
return f"{type(self).__name__}({repr(self.contents)})"
def get_score(self, parent_score=0):
"""
>>> Node.from_node_text('{}').get_score()
1
>>> Node.from_node_text('{{{}}}').get_score()
6
>>> Node.from_node_text('{{{},{},{{}}}}').get_score()
16
>>> Node.from_node_text('{<a>,<a>,<a>,<a>}').get_score()
1
>>> Node.from_node_text('{{<ab>},{<ab>},{<ab>},{<ab>}}').get_score()
9
>>> Node.from_node_text('{{<!!>},{<!!>},{<!!>},{<!!>}}').get_score()
9
>>> Node.from_node_text('{{<a!>},{<a!>},{<a!>},{<ab>}}').get_score()
3
"""
my_score = parent_score + 1
return my_score + sum(
content.get_score(my_score)
for content in self.contents
)
Node.group_class = Group
Challenge.main()
challenge = Challenge()