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?
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:
and then a small thing - the following two lines line =
line.strip(); data = line.split(" ")
can be replaced withdata = line.strip().split()