Advent of Code Day 5

Day 5

Solution to day 5 of Advent of Code https://adventofcode.com/2018/day/5

Data preparation

Since both part 1 and two use the same data, we create a function to read and prepare the data in the file:

In [1]:
def read_file():
    with open(r"datafiles\aoc5input.txt",'r') as f:
        line = f.read()
        return line

Part 1

Using deques

In [2]:
from collections import deque

def match(left,right):
    return left and left[-1] != right[0] and left[-1].lower() == right[0].lower()

def part1(s):
    left = deque()
    right = deque(s)
    while right[0] != '\n':
        if match(left,right):
            left.pop()
            right.popleft()
        else:
            left.append(right.popleft())

    return len(left)

part1(read_file())
        
Out[2]:
11546

Part 2

Lets do part 1 26 times.

In [3]:
from string import ascii_lowercase

s = read_file()

min([part1(s.replace(i,'').replace(i.upper(),'')) for i in ascii_lowercase])
    
Out[3]:
5124

links

social