Q: What are the 3 hardest problems in computer science?

A: Naming things, and off by one errors.

Let’s take a look at a common off-by-one error that we see in Python all the time. The range function is very useful for creating a sequence that can be used in loops. Here’s an example of how range might be used:

range in action

We see it counted out 10 things, but it started at 0 instead of 1. In some programming languages this is the norm, but for people coming from other languages this can cause confusion.

The range function can also start at a specified number, and this is when the off-by-one error really tends to bite people. Recently at work we had to write a script to scan through some servers and reboot them if there was a problem.

As we fixed the servers in the cluster we had to modify our checking script so that it would skip some machines. The developer who was working on this was new to Python and this error cropped up and caused problems.

Here’s a video walking through the issue. This code is a very simplified version of the code we were using. In the video I step through the code to show an approach to debugging this type of situation.

This is of course just one example of this type of error. It also occurs frequently when you are doing for loops, especially over arrays that have zero-based indexes. (Javascript, C, C++, I’m looking at all of you!)

I am planning to do more posts like this. If you would like to know when a new post is up, just sign up below! (I hate spam, so I promise I won’t sell you address or anything like that.)