python rewrite of the code