returning a palindrome at an index - Python -


def palindrome(s,index):      if s.islower() , s.isalpha():         num=1         if s[index-num]==s[index+num]:             num+=1             return s[index-num:index+(num+1)]         return s[index]      return '' 

i have return longest odd-length palindrome in string centered @ specified index , palindrome function not work example if >>>palindrome('noonoon',3) 'oonoo' rather 'noonoon'

def palindrome(s,index):     output=s[index]     before,after in zip(s[:index][::-1],s[index+1:]):         if before==after:             output=before+output+after         else: break     if output==s[index]: return ''     else: return output   >>> palindrome('youtubecat',3) 'utu' 

the for loop looping outward s[index]. before looping through 'uoy' (you reversed, hence [::-1] reverse splice) , after looping through 'ube'. while before , after same, it's being appended s[index]. aren't same, returns output. if palindrome cannot made index location, empy string returned.

just it's clear, after isn't looping through 'ubecat' because when zip both objects have same length, why it's truncated 'ube'.

>>> palindrome('racecar',3) 'racecar' 

if case isn't issue (ie 'a'='a') use lower() method in if statement:

if before.lower()==after.lower()

if want alternate way it:

def palindrome(s,index):     mirror=min([len(s[:index]),len(s[index+1:])])     s=s[index-mirror:index]+s[index:index+mirror+1]     while s:         if len(s)==1: return ''         if s==s[::-1]: return s # check if it's palindrome         else:                   # if not, remove first , last char             s=s[1:-1] 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -