Implementation of algorithm in Python