问题
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
回答1:
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]
回答2:
You move i every time, so you don't extend the index to both direction, but move your 3-letters-circle to the right every time. You need to keep the original index, and every time add or substruct equal increasing amount of index from the original index:
How you want it to be:
c o l o r
- i -
- i -
How it's doing:
c o l o r
- i -
- i -
So practically just save the index, and increment the margin. Also, you want to iterate only index margins, not the string, so:
def get_odd_palindrome_at (s, index):
palindrome = s[index]
for i in range(index):
if s[index - i] == s[index + i]:
palindrome = s[index - i] + palindrome + s[index + i]
else:
break
return palindrome
来源:https://stackoverflow.com/questions/40476020/get-odd-length-palindrome