Day 10
I was a bit slow today, but it was still a very interesting puzzle with some cool concepts!
A stack was most certainly the instant thought of thousands of programmers around the world for Part 1. When it comes to things like syntax (in the title of the puzzle) parsing or bracket evaluation, stacks are the key data structure to use. A stack is what it sounds like - putting items in and taking them out from the top. It's like a stack of books - the last one to go on the stack of books is the first one to leave the stack of books. The idea here is to keep a stack of opening brackets and every time we encounter a closing bracket, the top item in the stack should be the corresponding opening one. If not, then we know the brackets don't match up and hence we have found a faulty line. This can be a somewhat complex idea to grasp so take a while to understand it if this is new to you.
My code essentially does this and when it finds a mistmatch, it uses the dictionary y to find the corresponding the number value.
Part 2 was just adding some more code. If the line in the input is valid, we perform the next set of operations. I used the for...else structure here. The else part is run if the for part was not broken out of - and we broke out of the for part if the line was invalid, meaning that only valid lines would be run through the else part. Since I already had a stack of the opening brackets that needed to be closed, it was merely a matter of going through the stack from top to bottom (or right to left because I used a list to implement a stack) and obeying the rules in the question. A quick way to identify the new score of each bracket was using the index list k. To find the centre item in the list of answers, I just sorted it and found the half-way index. median() from the statistics module could also have been used without the need to sort it, or do any maths yourself!
A fun play with stacks today - will there maybe a more complex version coming later this month???