Return the longest oddlength palindrome in the string which

Return the longest odd-length palindrome in the string which is in the center at special index. >>> get_odd_palindrome_at (\"daabacc\", 3) \"aba\" >>> get_odd_palindrome_at(\"feacbcahj1\", 4) \"acbca\" >>>get_odd_palindrome_at (\"abc\", 1) \"b\"

Solution

Please follow the code and comments for description :

CODE :

def get_odd_palindrome_at(phrase, index): # function definition
palindromes = [] # empty list to append the data

for i in range(index): # iterate over the loop of the indexes
if index + i >= len(phrase): # check for the index if the last element of the string
break # break the loop
if phrase[index - i] == phrase[index + i]: # check for the palindrome string or the element
candidate = phrase[index - i: index + i + 1] # save the character to the varaible
palindromes.append(candidate) # add the varaible to the list
  
print(palindromes[-1]) # get the last index or the last string as the result
  
  
OUTPUT :

Run 1 :

get_odd_palindrome_at(\"feacbcahjl\", 4)
acbca

Run 2 :

get_odd_palindrome_at(\"daabacc\", 3)
aba

Run 3 :

get_odd_palindrome_at(\"abc\", 1)
b


Hope this is helpful.

 Return the longest odd-length palindrome in the string which is in the center at special index. >>> get_odd_palindrome_at (\

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site