core Python code for alg