I think you need to pare this down more. I started reading at line 1 and by line 20 I finally reached where you might be asking a question.

Since you know your use of the arrays and what it means, I think you need a python debugger tool. Or need to learn how to print values so you can see what your code and variables are at some line of code.https://www.google.com/search?q=python+debugging shows there is a debugger so if I was working this, I would be using that to check over the varialbes as it runs.