100 Days of Code - Day 1: Code Wars Kata
Tuesday, January 1, 2019 @ 09:33:00 PM EST
Reading time ~2 minutes
The new year has arrived, the holidays and vacations are finally behind me and school is long in the rear view mirror. In trying to keep my learning moving in a positive direction, I’m going to be pushing myself to complete 100 Days of Code! I’ve never attempted anything like this, and I look forward to seeing what I can accomplish over these next 100 days of 2019!
I’m easing my way in to it so I hopped on Code Wars and checked out some available Katas for Python. I came across one that piqued my interest called “Count the smiley faces!”. In this challange, I was given an array (or list) of strings, each item containing several characters. I needed to determine how many of them were valid smiley faces based on their specific criteria. This is seemed to be a simple regular expression problem that I felt would be good to start down this journey on the right foot. I intend to dig much deeper into various coding projects, but I was busy hosting our annual New Years Game Day, so I wanted to make sure I got something completed before the end of the day. With that said, let’s dig into this problem.
Based on their criteria, valid smileys consist of :) :D ;-D :~)
. Knowing this, I constructed a regex that would account for these variances. The eyes can be a colon or semi-colon, optional nose of a dash of tilde, and the mouth should be a capital ‘D’ or right parenthesis. Whenever I have a regex problem, I jump over to RegEx101 to make sure I have my syntax correct and can perform some practice samples. There I came up with "[:;][-~]?[)D]"
. Each group matches one of the characters within while the question mark labels the second grouping as optional.
Jumping over to my Python code I knew I would be using the re
module, and then I would use re.compile
to create a regex object that could be used for matching. I began creating a for
loop to iterate over the items within the list, and was using the re.match()
function to determine if the item was a match for the regular expression. However, this seemed like an over complication. I remembered back to a previous post I wrote about the Python filter
built-in function. I could use this to execute a function over an iterable, which would give me a filter
object with the results. I knew I could easily cast this as a list
and check its length to get the total count.
And it worked! A simple solution to a relatively simple problem.
import re
def count_smileys(arr):
r = re.compile(r"[:;][-~]?[)D]")
return len(list(filter(r.match, arr)))
So there it is, day 1 of 100 Days of Code! I only spent a few minutes on this one, but sometimes that’s what I’ll be able to get done, and that’s ok. Small steps are still steps forward.