Improved python algorithm