Python 这个函数检查回文的错误在哪里?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19365008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:33:55  来源:igfitidea点击:

Where's the bug in this function to check for palindrome?

pythonpalindrome

提问by Prakhar Mohan Srivastava

Given below is the code to check if a list is a palindrome or not. It is giving correct output for 983. Where am I going wrong?

下面给出的是检查列表是否为回文的代码。它为 983 提供了正确的输出。我哪里出错了?

def palindrome(num):
    flag=0
    r=num[::-1]
    for i in range (0, len(num)-1):
        if(r[i]==num[i]):
            flag=1
        else:
            flag=0
    return flag

采纳答案by Rohit Jain

You should return as soon as there is a mismatch. Also, you just need to iterate till half the length:

一旦出现不匹配,您应该立即返回。此外,您只需要迭代到长度的一半:

def function(...):
    ...
    for i in range (0, (len(num) + 1) / 2):
        if r[i] != num[i]:
            return False
    return True


BTW, you don't need that loop. You can simply do:

顺便说一句,你不需要那个循环。你可以简单地做:

def palindrome(num):
    return num == num[::-1]

回答by Synthetica

This would be easier:

这会更容易:

def palindrome(num):
    if num[::-1] == num:
       return True
    else:
       return False

回答by aga

Your forloop checks all pairs of characters, no matter if it found mismatch or not. So, in case of string '38113' it will return True, because the flagvariable will be set to Trueafter the check for equality of last digit in '38113' and its reversed version '31183' (both equal to 3, while the string isn't a palindrome).
So, you need to return Falseright after you've found mismatch; if you checked all the characters and didn't find it - then return True, like so:

for无论是否发现不匹配,您的循环都会检查所有字符对。因此,在字符串 '38113' 的情况下,它将返回True,因为该flag变量将True在检查 '38113' 中最后一位数字的相等性及其反转版本 '31183'(两者都等于 3,而字符串不是)之后设置为t 回文)。
因此,您需要False在发现不匹配后立即返回;如果您检查了所有字符并没有找到它 - 然后返回True,如下所示:

def palindrome(num):
    r = num[::-1]
    for i in range (0, len(num)-1):
        if(r[i] != num[i]):
            return False
    return True  

Also, as someone pointed out it'll be better to use python's slices - check out the documentation.

另外,正如有人指出的那样,使用 python 的切片会更好 - 查看文档

回答by user3459183

def palindrome(a):
     a=raw_input('Enter :')
     b=a[::-1]
     return a==b

回答by Jorge E. Hernández

Just for the record, and for the ones looking for a more algorithmic way to validate if a given string is palindrome, two ways to achieve the same (using whileand forloops):

只是为了记录,对于那些正在寻找一种更算法的方式来验证给定字符串是否为回文的人,两种实现相同的方法(使用whilefor循环):

def is_palindrome(word):

    letters = list(word)    
    is_palindrome = True
    i = 0

    while len(letters) > 0 and is_palindrome:       
        if letters[0] != letters[-1]:
            is_palindrome = False
        else:
            letters.pop(0)
            if len(letters) > 0:
                letters.pop(-1)

    return is_palindrome

And....the second one:

还有....第二个:

def is_palindrome(word):

    letters = list(word)
    is_palindrome = True

    for letter in letters:
        if letter == letters[-1]:
            letters.pop(-1)
        else:
            is_palindrome = False
            break

    return is_palindrome

回答by ankita

str1=str(input('enter string:'))
save=str1
revstr=str1[::-1]
if save==revstr:
     print("string is pailandrom")
else:
     print("not pailadrom")

回答by Anupam Thakur

# We are taking input from the user.
# Then in the function we are reversing the input i.e a using 
# slice     [::-1] and 
# storing in b
# It is palindrome if both a and b are same.

a = raw_input("Enter to check palindrome:") 
def palin():
    #Extended Slices to reverse order.
    b = a[::-1]
    if a == b:
        print "%s is palindrome" %a
    else:
        print "%s is not palindrome" %a
palin()

回答by user8211857

this would be much easier:

这会容易得多:

def palindrome(num):
    a=num[::-1]
    if num==a:
        print (num,"is palindrome")
    else:
        print (num,"is not palindrome")

x=input("Enter to check palindrome:")
palindrome(x)

回答by D S Tejendra

a="mom"
b='mom'[::-1]  # reverse the string
if a==b:  # if original string equals to reversed
    print ("palindrome ")
else:
    print ("not a palindrome ")

回答by D S Tejendra

Here in my opinion is the most elegant:

在我看来,这里是最优雅的:

def is_palindrome(s):
    if s != '':
        if s[0] != s[-1]:
            return False
        return is_palindrome(s[1:-1])
    return True

it's also the same code in the is_palindrome() function:

它也是 is_palindrome() 函数中的相同代码:

pip install is-palindrome


>>> from is_palindrome import is_palindrome
>>> x = "sitonapanotis"
>>> y = is_palindrome(x)
>>> y
True

Take care to note the hyphen vs underscore when installing vs. importing

安装和导入时注意注意连字符和下划线