Can you rewrite this to not use the itertools library?