繁体   English   中英

python中的回文逻辑:此程序有什么问题?

[英]Palindrome logic in python: What is wrong with this program?

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()

我认为程序中的所有内容都是正确的。 输入不是回文的单词会很好,但是输入回文时会出现如下错误:

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

您检查回文的逻辑应为:

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

如果您使用的是python l/2则可以执行l/2 ,但是python 3会将结果生成为浮点值。 您的代码似乎在py3中。

并且您需要elif块一个条件。 否则,将其更改为else

错误的第一件事是: elif: -如果您使用的是elif:如果您应提供条件,则在这种情况下将其更改为else:

其次, if应该是: if(word[i] != word[li-1]):为了使函数正常工作(检查每个字母是否等于单词中的等价字母)。

第三,不太重要,但仍然很重要:保持样式:

  1. 删除多余的括号
  2. 使用正确的命名约定(蛇形而不是驼峰)
  3. 使用True / False作为返回值,而不是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()

word[i+l-1]更改为word[li-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[li-1i向上计数时向下计数; 因此,您需要减去i而不是相加。

另外,我将l/2更改为l // 2以便它也可以在Python 3中使用。

希望有帮助:-)

您应该将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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM