Working Python implementation :)