Fix off-by-1 discrepancy between python and C++ versions