adding the python version, a direct translation but significantly slower than the C++.