I've written a function which, given a number string, returns the next largest palindrome in string form. For example, if the input string is "4738"
, the output should be "4774"
. The original problem description is found here. The function seems to be working for all the tests I have thrown at it so far, but the problem is that it is timing out when I submit it at the website above. Which parts are slow, and how can I improve the performance of this function?
# Algorithm: If replacing the right half of the original number with the
# mirror of the left half results in a bigger number, return that.
# Otherwise, increment the left half of the number, then replace the
# right half of the original number with the mirror of the new left half
# and return.
def next_palindrome(n):
X = len(n)>>1
Y = X+(len(n)&1)
first = n[:X][::-1]
second = n[Y:]
Z = n[:Y]
if int(first) > int(second): return Z+first
else:
bar = str(int(Z)+1)
return bar+bar[:X][::-1]