Port to python3; minor improvements
Port to python3
Optimize the algorithm a bit