Longest palindromes in a string
Do % p early.

Since the test case is huge, I expect intermediate values you compute to be huge as well. Multiplication of large numbers is a very expensive operation. Try to keep your results in a native range. Consider e.g.

def modulo_factorial(n, mod):
    result = 1
    for i in range(1, n + 1):
        result = (result * i) % mod
    return result


Ditto for pow.
Do not recompute factorials from scratch. Instead of

for i in divide:
    temp = factorial(i)
    temp = pow(temp, p - 2, p)
    total = total * temp


sort divide first. Then computation of each factorial can be started where the previous one ended. 

Also notice that since total is greater than any element of divide, you should compute factorial(total) after the this loop, using the same technique. 

And don't forget to % p early.
Most of your imports are never used.