Get Odd Length Palindrome
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_palindrom
Solution 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):
ifindex + i >= len(s) or s[index - i] != s[index + i]:
i -= 1breakreturn 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 = indexwhile i >= 0and j < len(s) and s[i] == s[j]:
i -= 1
j += 1return s[i+1:j]
Solution 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:
breakreturn palindrome
Post a Comment for "Get Odd Length Palindrome"