rewrite old java solution to python