Can this code be shorter? Bots, instructions and dictionaries

80 Views Asked by At

The idea for this task comes from Advent of Code, Day 10. Bots manipulate chips with numbers. Instructions are given as follows (they are located in a txt file).

bot 1 gives low to output 1 and high to bot 0
value 5 goes to bot 2
bot 0 gives low to output 2 and high to output 0
bot 2 gives low to bot 1 and high to bot 0
value 3 goes to bot 1
value 2 goes to bot 2

I had to write a function read_file(filename) that reads the file and returns a pair (tuple). The first element is the initial state and the second are the instructions.

As an example:

The initial state in this example is: {1: [3], 2: [5, 2]}

and the instructions are {0: (('output', 2), ('output', 0)), 1: (('output', 1), ('bot', 0)), 2: (('bot', 1), ('bot', 0))}

This is how I solved it.

bots = dict()
instructions = dict()
with open("example.txt") as f:
    linez = f.readlines()

for line in linez:
    line = line.strip()
    data = line.split(" ")
    if line.startswith("value"):
        value = int(data[1])
        bot = int(data[5])

        if bot not in bots:
            bots[bot] = []
        bots[bot].append(value)

    elif line.startswith("bot"):
        bot = int(data[1])
        low = (data[5], int(data[6]))
        high = (data[10], int(data[11]))
        instructions[bot] = (low, high)

I was wondering, if there was a shorter way to solve this problem?

2

There are 2 best solutions below

0
On

as the comment above says - not sure if you want shorter or faster code.

What you can do for a shorter code is to use defaultdict so you dont have to explicitly check if a certain key in dictionary exists already:

from collections import defaultdict
bots = defaultdict(list) # the param says what should be the default value

# the following three lines will be replaced with the line below
# if bot not in bots:
#     bots[bot] = []
# bots[bot].append(value)
bots[bot].append(value)

and then a small thing - the following two lines line = line.strip(); data = line.split(" ") can be replaced with data = line.strip().split()

0
On

Replace this:

with open("example.txt") as f:
    linez = f.readlines()

for line in linez:
    # code here

with:

with open("example.txt") as f:
    for line in f:
        # code here

It's both shorter (well, not by much but...) and more memory efficient ;)