Help needed in a past year ZCO question

I was doing a past year ZCO question and I am getting WA on some test cases and NZEC on 1 test case. I am not able to figure out problem in my code. Please check it and help me

https://www.codechef.com/viewsolution/39546657
this is the link for my code. It is written in Python 3 and I understand it is a little chaotic but please try to understand it and help me. If you are not able to understand what I did in a certain line then please ask me.

Thanks in advance