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:

For this challenge you will determine if the brackets in a string are correctly matched up.

Here are the 3 test strings I used:

sample1=’hi()’
sample2=’(hi’
sample3 = ‘[]hi’

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:

Have the function BracketMatcher(str) take the str parameter being passed and return 1 if the brackets are correctly matched and each one is accounted for. Otherwise return 0. For example: if str is “(hello (world))”, then the output should be 1, but if str is “((hello (world))” the the output should be 0 because the brackets do not correctly match up. Only “(“ and “)” will be used as brackets. If str contains no brackets return 1

Now we’re talking.

I created additional test strings:

test4 = “((hello(world))” 
test5 = ‘(hello(world))’

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?