68 lines
1.6 KiB
Python
68 lines
1.6 KiB
Python
import shared
|
|
from pprint import pprint as pp
|
|
import sys
|
|
|
|
OPEN = "([{<"
|
|
CLOSE = ")]}>"
|
|
PAIRS = dict(zip(OPEN, CLOSE))
|
|
PAIRS.update(zip(CLOSE, OPEN))
|
|
BAD_POINTS = dict(zip(CLOSE, [3, 57, 1197, 25137]))
|
|
GOOD_POINTS = dict(zip(CLOSE, [1, 2, 3, 4]))
|
|
|
|
|
|
def load_file(name):
|
|
with open(name, "r") as f:
|
|
my_file = []
|
|
for line in f:
|
|
my_file.append(line.rstrip())
|
|
return [x for x in my_file]
|
|
|
|
|
|
class Syntax:
|
|
def __init__(self, name):
|
|
self.parse(name)
|
|
|
|
def parse(self, name):
|
|
self.mx = load_file(name)
|
|
self.good_lines = []
|
|
|
|
def find_all(self):
|
|
bad_points = 0
|
|
all_points = []
|
|
for idx, line in enumerate(self.mx):
|
|
c, bad = self.find_chunks(line)
|
|
if bad:
|
|
bad_points += BAD_POINTS[c]
|
|
else:
|
|
match_points = 0
|
|
for x in c:
|
|
match_points *= 5
|
|
match_points += GOOD_POINTS[x]
|
|
all_points.append(match_points)
|
|
|
|
mp = list(sorted(all_points))
|
|
print(bad_points) # pt1
|
|
print(mp[len(mp) // 2]) # pt2
|
|
|
|
def find_chunks(self, line):
|
|
unpaired = []
|
|
for idx, char in enumerate(line):
|
|
if char in OPEN:
|
|
unpaired.append(char)
|
|
if char in CLOSE:
|
|
if unpaired[-1] != PAIRS[char]:
|
|
return char, True
|
|
unpaired.pop(-1)
|
|
# Line is good here
|
|
unpaired = list(reversed(unpaired))
|
|
return [PAIRS[u] for u in unpaired], False
|
|
|
|
|
|
def main():
|
|
s = Syntax(shared.get_fname(10))
|
|
s.find_all()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|