Extra Cheese

A Blog


String Calculator Kata in Python

Jan 06, 2010

For those who aren't familiar, katas are those impressive sequences of movements that you've surely seen martial arts guys perform. Code katas are the same idea applied to writing code: you solve a problem many times, mastering the movements, and then perform it for others.

My friend Corey Haines has worked with some other people to run a Katacast site dedicated to code katas, posting them roughly once per week. Recently, there's been a string of solutions to the same problem, with my Python version as this week's entry.

Briefly, here's the problem I solve. I have numbers coming in as a string, separated by commas or newlines. My job is to add those numbers and return the sum. There are two complications:

  1. If the first line of the string is of the form "//*", then * is also a possible delimiter. This works for any string, not just *.
  2. Negative numbers must be rejected.

You can see the kata and read my brief commentary on the Katacasts site, or go straight to Vimeo to watch it. It's only 4:32 long, so it's not a big commitment.

String Calculator Kata In Python from Gary Bernhardt on Vimeo.

My screencasts always prompt questions about my Vim configuration, so take a look at my dotfiles repo if you're interested. For this kata, I'm slowing down intentionally – typing slower and inserting small, regular pauses so the viewer has time to look around a bit. I may post a "hard mode" version at full speed if people show interest.

Comments are encouraged, of course – the purpose of a kata is improvement!

If you like this, by the way, you may also enjoy the refactoring screencast I posted recently.



Cyclomatic Complexity in Vim: First Steps

Oct 25, 2009

I've been kicking around the idea of integrating complexity analysis with vim. Tonight, I spent a couple hours getting a proof of concept working (for Python code, naturally). Each line gets highlighted based on the complexity of the function: green for low, yellow for medium, red for high.

A static image doesn't really do it justice – the highlighting updates whenever you write a file. There's a 15 second video of me demoing it that's much better than the picture above.

This is based on Dave Stanek's cyclomatic complexity code. It's hacked together and the complexity algorithm seems slightly wrong (unless I'm remembering it incorrectly). However, it does successfully compute the complexity and highlight the code, which is good enough for a blog post. ;)

If you're feeling adventurous, you can find the source code on BitBucket.