Part 1
In this part, we need to figure out the difference between the representation and the in-memory string. Specifically, we are interested in the difference in the length. For part 1, instead of manually writing a parser, the eval function already does want we want. We compare the length of the string before and after being eval'd to get the answer.
This was tested against the examples provided and for the puzzle, we loop over the input and sum the differences per line.
Part 2
In part 2, we need to encode a in-memory string into the representation. So basically the reverse of the previous task. There is probably a better option, but I just used string replacement to quote special characters. The function just returns the length, since we are only interested in the change after encoding.
def part_2(line):
line = line.replace('\\', '\\\\')
line = line.replace('"', '\\"')
line = '"' + line + '"'
return len(line)
Again this was tested against the examples and integrated into the loop from the previous part.
No comments:
Post a Comment