Part 1


In [19]:
l = ! cat input.txt | tr '\n' ';'
l = l[0].rstrip(';').split(';')[0]

In [20]:
def one_step(l):
    jump = False
    acc = ""
    n = len(l)
    for i in range(n - 1):
        if jump:
            jump = False
            continue
        if (l[i] != l[i+1]) and ((l[i].lower() == l[i+1]) or (l[i].upper() == l[i+1])):
            acc += ""
            jump = True
        else:
            acc += l[i]
            if i == n - 2:
                acc += l[i+1]
    return acc

def fully_react(l):
    diff = len(l)
    while diff > 0:
        red  = one_step(l)
        diff = len(l) - len(red)
        l = red
    return red

In [21]:
reduced = fully_react(l)
len(reduced)


Out[21]:
9462

Part 2


In [25]:
from tqdm import tqdm

def test_reductions():
    best_len = len(l)
    for c in tqdm('abcdefghijklmnopqrstuvwxyz'):
        rem = ''.join(''.join(l.split(c)).split(c.upper()))
        n   = len(fully_react(rem))
        if n < best_len:
            best_len = n
    return best_len

In [26]:
test_reductions()


100%|██████████| 26/26 [04:19<00:00,  9.08s/it]
Out[26]:
4952