简体   繁体   English

确定字符串是否为回文序列

[英]Determining whether a string is a Palindrome

I wrote the following program to determine whether a string sa palindrome using recursion. 我编写了以下程序来确定字符串是否使用递归的回文。 My problem is that I am not sure how to add a print statement that tells me whether the string is a palindrome or not. 我的问题是我不知道如何添加一个print语句,告诉我该字符串是否是回文。 I realize that there are other codes which do the same thing, but I am trying to understand if my reasoning is correct. 我意识到还有其他代码可以做同样的事情,但我想知道我的推理是否正确。

import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring =newstring.lower()

def Palind(newstring):

    if newstring[0] != newstring[-1]:
        #print 'The given string is not a palindrome'
        return False 
    else: 
        s_remain = newstring[1:-1]
        if s_remain == '':
            return True
        elif len(s_remain) == 1 :
            return True
        else:
            return Palind(s_remain)


if Palind(newstring):
    print 'Yes'
else: 
    print 'No'  

First, correctly indent your code, and properly lowercase the input: 首先,正确缩进代码,并正确地小写输入:

import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring = newstring.lower()

def Palind(newstring):    
    if newstring[1] != newstring[-1]:
        #print 'The given string is not a palindrome'
        return False 
    else: 
        s_remain = newstring[1:-1]
        return Palind(s_remain)

Then actually call your function and deal with the result: 然后实际调用你的函数并处理结果:

if Palind(newstring):
    print ('Yes')
else:
    print ('No')

That's how you print the result of your function.. 这就是你打印函数结果的方法..

You will have problems when you enter a palindrome though, because you never actually return true. 当你进入回文时,你会遇到问题,因为你从未真正回归真实。 You'll need to fix that by checking if you've gotten to the end of the string without returning false. 你需要通过检查你是否已经到达字符串的末尾而不返回false来解决这个问题。

Your logic is roughly right, but you are missing some things. 你的逻辑是大致正确的,但你错过了一些东西。

  1. The first character in a string is string[0] not string[1] , so you are comparing the wrong characters. 字符串中的第一个字符是string[0]而不是string[1] ,因此您要比较错误的字符。

  2. You need to call Palind() as well as def ining it. 你需要调用Palind()以及def进不去了。

  3. If you correct those problems, you are taking one letter off each side of the string each time, it gets shorter and shorter - the next interesting thing that happens is you either get down to a single character or you run out of characters. 如果你纠正了这些问题,你每次都会在字符串的每一边都掉一个字母,它会变得越来越短 - 下一个有趣的事情就是你要么得到一个字符,要么你的字符用完了。 You should be looking for that state. 你应该寻找那个州。

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

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