Python Any Idea To Optimise This Algorithm Stack Overflow

Python Any Idea To Optimise This Algorithm Stack Overflow