time limit exceeded...

What can I do in order to avoid time limit exceeded for the problem LYRC from practice(hard) section? Could somebody please give me few suggestions? The link to the code I wrote in python 3.1.2 is given below.

link text

Use an efficient algorithm.

//