Python version roughly equivalent to C++ version