2013-11-24 69 views
0

更新:感謝以下答案,我現在知道它是函數中的錯誤,並且與Python的行爲無關。 (我的犯規)我已經把標題從「可以在迭代字符串時跳過空格嗎?」到「這個功能有什麼錯誤?」所以未來的讀者會知道他們在這裏找到的答案與函數有關,而不是Python。這個迴文功能有什麼問題?

我在Python中做了一個函數,它確定一個字符串是否是迴文。基本上,它同時從左側和右側迭代,並檢查是否有任何字符不相等。如果是,則返回False。到達中間位置後,它停止迭代並返回True。

def isPalindrome(string): 
    l = 0 
    r = -1 
    while(l < r+2): 
     if string[l] != string[r]: 
      return False 
     l += 1 
     r -= 1 

    return True 

palin = raw_input("Enter string: ") 
if(isPalindrome(palin)): 
    print "\""+palin+"\"","is a Palindrome." 
else: 
    print "\""+palin+"\"","isn't a Palindrome." 

它的工作原理 ,但由於某種原因它也指出像「pythonnoh TY P」作爲一個迴文字符串。儘管有時這可能是件好事,但我想知道爲什麼函數會跳過字符串中的空格。它應該返回False,因爲''不等於'y',但它不會。

在我的代碼中是否有問題,或者它是Python的行爲?

+4

你只比較第一和最後一個字母。根據你的功能,「pythonp」也是一個迴文。與空格無關。 – Hyperboreus

回答

4

lr比較string[0]string[-1]的值均1-2。由於1 < 0不正確,您的while循環結束。

試試這個:

def isPalindrome(s): return s == s[::-1] 

如果要忽略空格,你可以擴展它一點:

def isPalindrome(s, ignoreSpaces = False): 
     if ignoreSpaces: 
       s = s.replace(' ', '') 
     return s == s[::-1] 

print (isPalindrome ('pythonnohtyp')) 
print (isPalindrome ('pythonnohtyp', True)) 
print (isPalindrome ('pythonnoh ty p')) 
print (isPalindrome ('pythonnoh ty p', True)) 
3

看來你的while循環有問題。

我添加了一個快速調試語句,併爲您運行一些測試,以發現問題。

>>> def isPalindrome(string): 
    l = 0 
    r = -1 
    while(l < r+2): 
     if string[l] != string[r]: 
      return False 
     print "left: %s" %string[l] 
     print "right: %s" %string[r] 
     l += 1 
     r -= 1 

    return True 

>>> isPalindrome("ono") 
left: o 
right: o 
True 
>>> isPalindrome("on o") 
left: o 
right: o 
True 
>>> isPalindrome("palindrome") 
False 
>>> isPalindrome("palinilap") 
left: p 
right: p 
True 
>>> isPalindrome("palinalap") 
left: p 
right: p 
True