Working python implementation