Python Code Challenge: Bracket Matching

A journey of five different versions

Calm water ripple
Photo by Jeremy Bishop on Unsplash

Last week I played around with one of the harder code challenges for beginners on Coderbyte and found it draining. Perhaps it can be blamed on the extraordinary circumstances of 2020 or maybe it was just the slow pace of August that caught me. In any case, this week I decided to try another code challenge — move up to the medium level — instead of tackling a refactor of last week’s code. This week’s challenge started as:

Here are the 3 test strings I used:

I started very basic; here is version 1 of my bracket_matcher():

And it worked!

Then realized how much simpler my code could be by using the “in” statement. So version 2 quickly followed:

This worked too for all three tests!

And then I decided that square brackets should be checked, in addition to, parentheses. This lead to version 3 and a list of two brackets to check against:

At this point, the solution had come so easily that it made me question the true description of the code challenge. After poking around on Coderbyte, I found a more descriptive version of the challenge:

Now we’re talking.

I created additional test strings:

And created my fourth version of bracket_matcher():

By now, the wheels were turning. Is there an even sleeker way to write this? And what if the brackets are not in the correct order — the right parentheses comes before the left in the string? This lead to version 5:

I particularly like how the final version uses a list comprehension to return the answer and how the function can handle incorrectly ordered parenthesis. This week, working on a Python code challenge felt more therapeutic than draining. It was pleasant to get lost in the code and forget about the world’s problems for a moment. Who knew coding could be a self-care activity?