Classical computer science problem with Python