Need help optimizing this code

Do keep in mind that printing at this rate causes a lot of lag. I’d recommend removing the print calls before looking into the necessary optimisations.

You should also take a look at this post.