How can I implement this algorithm in python code?