Converting an algorithm into a python code