I haven't done a Code Wars challenge in a little bit, so I logged in and grabbed my next challenge.
This one looks pretty easy, but let's walk through it.
Our starting code looks like this:
We are given a few example tests, but the solution will be run through more random tests as well.
As always, let's identify the problems we need to solve.
- Process each character of the input string
- Count each occurrence of any vowel outside of Y
- Return count
Seeing as I don't know any built-in that understands vowels, we are going to need to make our own collection. Let's use a set.
Using a set allows us to specify our collection and ignore Y easily.
We are going to next iterate through each value of the string. Let's do that with a for loop.
Let's test this, as this looks like a complete solution.
All tests pass! There is a lot of code here for such a simple problem, if you remember my previous lessons we had some more python ways to handle this sort of problem. I also don't think we need a counter variable. Let's refactor!
We can eliminate half the code by using a list comprehension.
This is much cleaner, and passes all test. But we can do better.
Let's remove the counter variable and just return directly. This cuts our solution down to 2 lines of code. This is likely as succinct as you can get for this problem, but I want to bring up one caveat. While returning the count directly we have eliminated most of the useless code, we do open ourselves to one problem. I'll tell you about that in a second, let's submit this and compare to other solutions first.
Complete series of tests pass, we have a good solution.
There is always someone smarter and more clever. The top solution is a single line of code. I am not convinced it is better though. It is a little harder to read, and not as obvious, but still good code. I'm happy with our solution and that's the way I would do it even after reviewing "better" solutions.
Now earlier I mentioned we have a caveat with our solution. Namely the fact we performed an action and directly returned it. While this is good a lot of the time, keep in mind in real world coding you likely want to do some validation on your output before returning it. In this case the code is pretty simple and trust worthy, many cases you will want to validate prior to using return. Keep that in mind when coding, ask yourself is this output sanitized, does it need error handling, are there scenarios this may fail? This probing questions will help you find bugs before they become bugs.
Hope you enjoy this lesson, if you like this series let me know in the comments.