I'm trying to find the longest odd length palindrome, but the code I've written isn't giving me the full palindrome, just part of it. Any help would be great!
def get_odd_palindrome_at(s, index):
''' (str, int) -> str
> get_odd_palindrome_at('tbababt', 3)
'tbababt'
> get_odd_palindrome_at('color', 2)
'olo'
'''
palindrome = s[index]
i = index
for char in s:
if s[i - 1] == s[i + 1]:
palindrome = s[i - 1] + palindrome + s[i + 1]
i = i + 1
return palindrome
Make i
the distance from the index
and make sure not to loop out of bounds. Finally, only build the result string when you have found the final value of i
. There is no use in doing it in every iteration:
def get_odd_palindrome_at(s, index):
for i in range(1, index+1):
if index + i >= len(s) or s[index - i] != s[index + i]:
i -= 1
break
return s[index-i:index+i+1]
Alternatively, you could use two variables, which simplifies the code a bit:
def get_odd_palindrome_at(s, index):
i = index
j = index
while i >= 0 and j < len(s) and s[i] == s[j]:
i -= 1
j += 1
return s[i+1:j]