2017-08-26 95 views
2
def isPalindrome(word): 

    l = len(word) 

    for i in range(l/2): 
     if(word[i] != word[i+l-1]): 
      return 0 

    return 1 

def main(): 

    print("\n\n\tTo Check if the word is a Palindrome\n\n") 

    word = raw_input("Enter a word : ") 

    if(isPalindrome(word) == 1): 
     print("It is a Palindrome") 

    elif: 
     print("It is not a Palindrome") 

main() 

在我看來,在程序中一切正常。python中的迴文邏輯:這個程序有什麼問題?

Enter a word : madam 
Traceback (most recent call last): 
    File "temp.py", line 16, in <module> 
    File "temp.py", line 6, in isPalindrome 
IndexError: string index out of range 
+4

什麼是錯的是不是一個合適的問題,你收到了什麼錯誤,你有什麼期望輸出 - 什麼你會得到嗎?例如。在'python3'範圍內(1/2)''會出錯,因爲'/'會返回一個'float'(使用''''')是你得到的錯誤? – AChampion

回答

2

您檢查迴文邏輯應該是::

if(word[i] != word[l-1-i]): 
    return 0 

沒關係的,當我輸入一個單詞是不是迴文,但是當我進入一個迴文它給出這樣的錯誤它去好要做l/2如果你在python 2上,但是python 3會產生結果作爲浮點值。 你的代碼似乎在py3中。

而你需要elif塊提供一個條件。否則,請將其更改爲else

這是錯誤的
2

的第一件事是:elif: - 如果你正在使用別的,如果你要提供一個條件,在這種情況下,修復其將其更改爲else:

其次,if應該是:if(word[i] != word[l-i-1]):爲了使該功能起作用(檢查每個字母是否等於該字中的等同字母)。

三,不太重要但仍然很重要:保持造型:

  1. 去除多餘的括號
  2. 使用正確的命名約定(蛇情況 - 沒有駝峯)
  3. 使用真/假的返回值,而不是1/0
  4. 使用地板師//(如AChampion在評論中提到的)

完整代碼(固定):

def is_palindrome(word): 
    l = len(word) 
    for i in range(l//2): 
     if word[i] != word[l-i-1]: 
      return False 
    return True 


def main(): 
    print("\n\n\tTo Check if the word is a Palindrome\n\n") 
    word = raw_input("Enter a word : ") 
    if is_palindrome(word): 
     print("It is a Palindrome") 
    else: 
     print("It is not a Palindrome") 


if __name__ == "__main__": 
    main() 
+1

雖然看起來OP使用的是Py2,但使用適用於py2和3的'range(l // 2)'可能更安全。 – AChampion

1

變化word[i+l-1]word[l-i-1]

def isPalindrome(word): 

    l = len(word) 

    for i in range(l // 2): 
     if(word[i] != word[l-i-1]): 
      return 0 

    return 1 

我們的目標是讓word[l-i-1倒計時,而i向上計數;因此,您需要減去i而不是添加它。

此外,我會將l/2更改爲l // 2,這樣它也可以在Python 3中使用。

希望幫助:-)

1

你應該四捨五入的L/2的值

def isPalindrome(word): 
    l = len(word) 
    for i in range(round(l/2)): 
     if(word[i] != word[i+l-1]): 
      return 0 
     return 1 

print("\n\n\tTo Check if the word is a Palindrome\n\n") 

word = input("Enter a word : ") 
if(isPalindrome(word) == 1): 
    print("It is a Palindrome") 
else: 
    print("It is not a Palindrome")