Better PHP and Python algorithm