Excactly the same as the Go version, just written in python