Python 中的简单回文检查?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18959658/
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 12:24:34  来源:igfitidea点击:

Simple Palindrome check in Python?

pythonstringreverseslicepalindrome

提问by user2257342

I am doing a palindrome check program for school, but there is a twist.

我正在为学校做一个回文检查程序,但有一个转折。

Now I already know that I could use a reverse function or something like:

现在我已经知道我可以使用反向函数或类似的东西:

[-1::-1]

However, the program specifically calls for no string slicing or use of the .reverse() function. So, my question is how would I go about doing this if I cannot use these two simple methods?

但是,该程序特别要求不进行字符串切片或使用 .reverse() 函数。所以,我的问题是,如果我不能使用这两种简单的方法,我该怎么做?

回答by georg

You actually don't need any reversefunction at all to check if something is a palindrome. Consider:

您实际上根本不需要任何reverse函数来检查某些东西是否是回文。考虑:

  • an empty string is a palindrome
  • a string of length 1 is a palindrome
  • every other string is a palindrome if its first and last characters are equal and the "middle" part (without the first and the last chars) is a palindrome, recursively.
  • 空字符串是回文
  • 长度为 1 的字符串是回文
  • 如果每个其他字符串的第一个和最后一个字符相等并且“中间”部分(没有第一个和最后一个字符)是一个回文,则每个其他字符串都是一个回文,递归。

Try to implement this in python - it's easy! (Hint: the last char is str[-1]and the middle is str[1:-1]).

尝试在 python 中实现它 - 这很容易!(提示:最后一个字符是str[-1],中间是str[1:-1])。

回答by Diego Herranz

It's clear that this is for academic purposes only because using reversed function this code would be trivial.

很明显,这仅用于学术目的,因为使用反向函数此代码将是微不足道的。

def is_palindrome(string):
    for i,char in enumerate(string):
        if char != string[-i-1]:
            return False
    return True

>>> is_palindrome('hello')
False    
>>> is_palindrome('helloolleh')
True
>>> is_palindrome('')
True
>>> is_palindrome(' ')
True
>>> is_palindrome('a')
True

回答by J0HN

Canonical solution would be:

规范的解决方案是:

def is_palindrome(string):
    result = True
    str_len = len(string)
    for i in range(0, int(str_len/2)): # you need to check only half of the string
        if string[i] != string[str_len-i-1]:
            result = False
            break
    return result # single return statement is considered a good practice