2016-11-10 87 views
1
def palindrome(s,index): 

    if s.islower() and s.isalpha(): 
     num=1 
     if s[index-num]==s[index+num]: 
      num+=1 
      return s[index-num:index+(num+1)] 
     return s[index] 

    return '' 

我不得不返回最長的奇數長度的迴文是指定索引處爲中心的字符串中,我回文功能例如不工作,如果我這樣做>>>迴文( 'noonoon',3)我得到 'oonoo' 而不是 'noonoon'指數在返回迴文 - Python的

+1

提示:你沒有循環任何事情。如果您只有一個,那麼您的代碼不會返回任何內容,一個字母或5個字母。 – matanso

+0

@matanso謝謝你的提示,但我不能找出一種循環方式 – CAVS

+0

('我應該返回一個給定的索引迴文'有'[index:index + 1]':)請指定什麼迴文返回:從索引處開始最長?最長以索引爲中心?還有別的嗎? – greybeard

回答

0
def palindrome(s,index): 
    output=s[index] 
    for 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' 

for環向外s[index]循環。所以before通過'uoy'you反轉,因此[::-1]反向拼接)和after循環通過'ube'。雖然beforeafter是相同的,但它被追加到s[index]。只要它們不一樣,它就會返回輸出。如果不能從index位置創建迴文,則返回empy字符串。

正是這樣很明顯,after不是通過'ubecat'循環,因爲當你zip兩個對象必須是相同的長度,這就是爲什麼它截斷爲'ube'

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

如果情況不是問題(即'A'='a'),然後使用在if聲明lower()方法:

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

如果你想要一個替代的方式來做到這一點:

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 a palindrome 
     else:     # if not, remove the first and last char 
      s=s[1:-1] 
+0

是的noonoon示例它但是如果我喜歡迴文('youtubecat',3)它給我'youtuoy'而不是utu – CAVS

+0

我想我不清楚,我必須返回以指定索引爲中心的字符串中最長的奇數長迴文。 – CAVS

+0

@CAVS,更新了回覆。沒有意識到這是你想要做的。 – LMc

0

您通過串需要循環:

def palindrome(s,index): 

    if s.islower() and s.isalpha(): 
     num=0 
     while index > num and index + num + 1 < len(s) and s[index-num-1]==s[index+num+1]: 
      num+=1 
     return s[index - num : index + num + 1] 
    return '' 
+0

我現在''ono' – CAVS