Port algorithm to python 3, 0.97s