Weekly Coding Challenge: Count the number of Exes and Ohs in Python

Posted by

2 min read ~ Hello readers! It’s really important for me to continue my practice and learning. Every week, I block off 30 minutes, set a timer and choose a challenge from codewars. This helps me keep my skills sharp, see how other devs all over the planet would solve these problems, and take some leisure time to problem solve and be creative. Being able to see other solutions expands my mind for solving future problems in a clever and efficient way. Today, the problem set focuses on Python.

Check to see if a string has the same amount of ‘x’s and ‘o’s. The method must return a boolean and be case insensitive. The string can contain any char.

Examples input/output:

XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
def xo(s):
    return s.lower().count('x') == s.lower().count('o');

I love solving simple problems like this using native functions from a language. Here, we simply convert the string to lower case before we use the count function to evaluate the amount of times the character occurs in the string. First, we do that for x and then we do that for o. Per the instructions, since we know we want to return a boolean, we can take each of those expressions, set them equal to each other and use that as our return value for the function.

All solutions are also now on my GitHub profile if you want to check out all of the coding challenges I’ve completed so far!

All credit to problem sets goes to codewars

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s