Code in Python of the algorithm in the database