2017-12-09 - Stream Processing
(original .ipynb)
def preprocess(raw_input_str):
input_str = ""
cancel_next = False
inside_garbage = False
garbage_count = 0
for c in raw_input_str:
if cancel_next:
cancel_next = False
continue
if c == "!":
cancel_next = True
else:
if c == "<":
if inside_garbage:
garbage_count += 1
inside_garbage = True
elif c == ">":
inside_garbage = False
elif not inside_garbage:
input_str += c
else:
garbage_count += 1
print(f"removed {garbage_count} of garbage")
return [ s for s in input_str ]
def parse(tokens):
group = []
while len(tokens) > 0:
token = tokens.pop(0)
if token == "{":
group.append(parse(tokens))
elif token == "}":
break
elif token == ",":
group.append(token)
return group
def all_scores(group, score=1):
return score + sum([all_scores(g, 1 + score) for g in group if isinstance(g, list)])
def solve_part_one(input_str):
tokens = preprocess(input_str)
groups = parse(tokens)[0]
total = all_scores(groups)
return total
from pprint import pprint
assert 1 == solve_part_one("{}")
assert 6 == solve_part_one("{{{}}}")
assert 5 == solve_part_one("{{},{}}")
assert 16 == solve_part_one("{{{},{},{{}}}}")
assert 1 == solve_part_one("{,,,}")
assert 9 == solve_part_one("{{},{},{},{}}")
assert 9 == solve_part_one("{{},{},{},{}}")
assert 3 == solve_part_one("{{},{},{},{}}")
removed 0 of garbage
removed 0 of garbage
removed 0 of garbage
removed 0 of garbage
removed 4 of garbage
removed 8 of garbage
removed 0 of garbage
removed 17 of garbage
puzzle_input = open("puzzle_input/day9.txt").read()
solve_part_one(puzzle_input)
removed 6425 of garbage
12803
# preprocess("<>") #0 characters.
# preprocess("") #17 characters.
# preprocess("<<<<>") #3 characters.
# preprocess("<{!>}>") #2 characters.
# preprocess("") #0
# preprocess(">")
# preprocess("<{o\"i!a,<{i")