回文与对称以及如何处理2字字符

Palindrome vs Symmetry and how to deal with 2 word character

2个字的单词能说是回文吗?比如“oo”是回文而“go”不是?

我正在执行一个从 GeeksForGeeks 检测回文的程序,但它也将 go 检测为回文,尽管它不是:

# Function to check whether the 
# string is plaindrome or not  def palindrome(a): 
   
    # finding the mid, start  
    # and last index of the string 
    mid = (len(a)-1)//2
    start = 0
    last = len(a)-1
    flag = 0
  
    # A loop till the mid of the 
    # string 
    while(start<mid): 
   
        # comparing letters from right 
        # from the letters from left 
        if (a[start]== a[last]): 
              
            start += 1
            last -= 1
              
        else: 
            flag = 1
            break; 
              
    # Checking the flag variable to  
    # check if the string is palindrome 
    # or not 
    if flag == 0: 
        print("The entered string is palindrome") 
    else: 
        print("The entered string is not palindrome") 

# ... other code ...          
          
# Driver code
string = 'amaama' 
palindrome(string)

是否有特定的长度或条件定义一个单词是回文?我看了Wikipedia article,但是没有发现关于回文长度的任何特定条件。

上述程序将“go”检测为回文,因为中点为0,也就是“g”,起点为0,也为“g”,所以判断为回文。但是我仍然对字符数感到困惑。 2个数字的单词可以是回文吗?如果是,那么我们是否需要为其添加特定条件:if word[0] == word[1]?

我们来看看回文的定义,according to Merriam-Webster:

a word, verse, or sentence (such as "Able was I ere I saw Elba") or a number (such as 1881) that reads the same backward or forward

因此,双字符词(或任何偶数字符词)也可以是回文。示例代码只是写得不好,在两个字符的字符串的情况下不能正常工作。正如您正确推断的那样,如果字符串的长度为 2,它将 mid 变量设置为 0。然后立即跳过循环 while (start < mid),因为 start也初始化为0。因此,flag变量(初始化为0,对应'is a palindrome')永远不会改变,所以函数错误地打印出go是一个回文.

您可以通过多种方式调整算法;最简单的方法是通过将 while 条件更改为 start <= mid 来简单地检查 并包括 中间字符索引。请注意,这只是 适应 给定代码的最简单方法,最简单的 Python 代码检查字符串是否回文要简单得多(因为您可以轻松地反转使用 a[::-1] 的字符串,并将其与原始字符串进行比较)。

(编辑添加:trincot 的另一个答案实际上表明所提供的算法对于所有偶数字符的单词都不正确。此答案中建议的修复仍然有效。)

你的问题很有道理。您引用的 GeeksForGeeks 中的代码没有给出正确的结果。事实上,对于较长的单词,如“gang”,它也会产生错误的结果。

The above program detects "go" as palindrome because the midpoint is 0, which is "g" and the starting point is 0, which is also "g", and so it determines it is a palindrome.

这确实是算法出错的地方。

...then do we need to just add a specific condition for it: if word[0] == word[1]?

鉴于while条件是start<mid,中点应该是第一个索引之后必须验证的字符串的前半部分,并且所以对于 2 个字母的单词,中点应该是 1,而不是 0。

改正程序中的错误很容易。变化:

mid = (len(a)-1)//2

收件人:

mid = len(a)//2

这解决了问题。不需要额外的代码行来将其视为一个单独的案例。

I did not find any particular condition on the length of a palindrome.

你是对的:没有这样的条件。 GeeksForGeeks 的代码让你怀疑,但是你一开始就对了,代码错了。