working python implementation