DEV Community

loading...

Discussion on: Advent of Code 2020: Python Solution Day 14

Collapse
rozbrajaczpoziomow profile image
rozbrajaczpoziomow

So I have smaller code for part 1. (I'd like to note, that instead of changing the file on-the-fly, i just assign the variable prompt as (in this case) an array of strings of every line)

import re
prompt = (input)
bitmask = -1
memory = []

def pad36(pad):
    return ('0' * (36 - len(pad))) + pad

for command in prompt:
    if(command.startswith('mask')):
        bitmask = re.findall(r'mask = (.*)', command)[0]
    elif(command.startswith('mem')):
        index = int(re.findall(r'mem\[(.*)\]', command)[0])
        value = int(re.findall(r' = (.*)', command)[0])
        valuebin = pad36(bin(value)[2:])
        finalbin = ''
        for iMask in range(0, len(bitmask)):
            if(bitmask[iMask] == 'X'):
                finalbin += valuebin[iMask]
            else:
                finalbin += bitmask[iMask]
        final = int(finalbin, 2)
        while(len(memory) <= index + 5):
            memory.append(0)
        memory[index] = final


print('[Solv]', sum(memory))
Enter fullscreen mode Exit fullscreen mode
Collapse
qviper profile image