Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def parse_snail(line):
- return eval(line) # Unsafe.
- def explode_one(snail) -> bool:
- def add_to_middle(snail, side, value):
- side1 = 1 - side
- while not isinstance(snail[side], int):
- snail = snail[side]
- side = side1
- snail[side] += value
- def recurse(snail, depth=0):
- for i, child in enumerate(snail):
- if not isinstance(child, int):
- if depth == 3:
- snail[i] = 0
- add_to_middle(snail, 1 - i, child[1 - i])
- child[1 - i] = None
- return True, child
- done, left_right = recurse(child, depth + 1)
- if done:
- if left_right[1 - i] is not None:
- add_to_middle(snail, 1 - i, left_right[1 - i])
- left_right[1 - i] = None
- return done, left_right
- return False, [None, None]
- return recurse(snail)[0]
- def split_one(snail) -> bool:
- for i, child in enumerate(snail):
- if isinstance(child, int):
- if child >= 10:
- snail[i] = [child // 2, (child + 1) // 2]
- return True
- elif split_one(snail[i]):
- return True
- return False
- def reduce_snail(snail):
- while explode_one(snail) or split_one(snail):
- pass
- return snail
- def magnitude(snail):
- return (snail if isinstance(snail, int) else
- 3 * magnitude(snail[0]) + 2 * magnitude(snail[1]))
- def process1(s, part2=False):
- lines = s.strip('\n').split('\n')
- snails = [parse_snail(line) for line in lines]
- if not part2:
- snail = snails[0]
- for i in range (1, len(snails)):
- snail = reduce_snail([snail, snails[i]])
- return magnitude(snail)
- return max(magnitude(reduce_snail(copy.deepcopy([snail0, snail1])))
- for snail0, snail1 in itertools.permutations(snails, 2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement