Need some optimization LEAFEAT iarcs judge

my code is TLE’ing for a few cases and I am unable to optimize it further…

any suggestions?

My Code

You can check the solution here - https://www.commonlounge.com/discussion/9745fd63556746efb70ddc015b7bf3cc

um… ive done the very same thing, the problem is pretty easy, i just dont know why its not running under the time constraints…