Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7.6:使用for循环生成回文检查器_Python_Palindrome - Fatal编程技术网

Python 2.7.6:使用for循环生成回文检查器

Python 2.7.6:使用for循环生成回文检查器,python,palindrome,Python,Palindrome,我正在做一个回文检查器,它需要内置一个for循环,逐字符检查单词,因为回文检查器必须工作,即使使用点、小写/大写字母等。例如:Sirap I Paris!我必须努力写作 我一直在试着对我写下的想法进行评论。我在Python方面做的工作很少,而且是一个真正的新手,所以在回答时请记住 提前多谢 (这段代码在18日出现了运行错误代码,我想知道为什么,我想知道是否有人对如何让代码1)工作得更简单2)我觉得我做得太过分了?) 这是我最好的办法 from string import punctuation

我正在做一个回文检查器,它需要内置一个for循环,逐字符检查单词,因为回文检查器必须工作,即使使用点、小写/大写字母等。例如:Sirap I Paris!我必须努力写作

我一直在试着对我写下的想法进行评论。我在Python方面做的工作很少,而且是一个真正的新手,所以在回答时请记住

提前多谢

(这段代码在18日出现了运行错误代码,我想知道为什么,我想知道是否有人对如何让代码1)工作得更简单2)我觉得我做得太过分了?)


这是我最好的办法

from string import punctuation
#punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""

def checkPalindrome(word):
    word = word.lower() #lowercase it all to ignore upper/lowercase fails
    word = word.translate(None,punctuation) #strips all the punctuation from the word
    #note that this won't work in Python 3.x, since str.translate() doesn't accept its
    #  optional second argument anymore. For 3.x you'd have to do
    #w = str.maketrans('','',punctuation)
    #word = word.translate(w)

    for i in range(len(word)): #this loop compares each letter with the same letter
        if word[i] != word[(i+1)*-1]: #counted from the end.
            return False #if they're not the same, return False
    return True #return True if you get here, which would mean none of the letters mismatched their partner
从字符串导入标点符号
#标点符号=r“”!“#$%&'()*+,-./:@[\]^_`{|}~"""
def检查回文(word):
word=word.lower()#将其全部小写以忽略大写/小写将失败
单词=单词。翻译(无,标点符号)#去掉单词中的所有标点符号
#请注意,这在Python3.x中不起作用,因为str.translate()不接受其
#可选的第二个参数。对于3.x,您必须
#w=str.maketrans(“”,,,标点符号)
#单词=单词。翻译(w)
对于范围内的i(len(word)):#此循环将每个字母与相同的字母进行比较
如果单词[i]!=word[(i+1)*-1]:#从末尾开始计算。
return False#如果它们不相同,则返回False
return True#如果你到了这里,就返回True,这意味着没有一个字母与他们的搭档不匹配

使用循环执行此操作的最简单方法是利用python负索引从序列的右侧开始计数的事实。因此,您希望执行以下操作:

def pal(maybepal):
    for left in range(len(maybepal)):
        right = -1 - left
        if maybepal[left] != maybepal[right]: return False
    return True

显然,您可以使这更有效(现在,这将检查每一对两次)。

不适用于循环,但使用理解相当简单

def ispalindrome(a):
a1=[x.upper()表示a中的x,如果x.isalpha()]
返回a1==a1[:-1]
若你们真的需要一个for循环,你们可以用更复杂一点的simlpe返回代替它

def ispalindrome(a):
  a1 = [x.upper() for x in a if x.isalpha()]
  for ix in xrange(len(a1)):  # or xrange((len(a1)+1)/2) to check each char once
     if a1[ix] != a1[-ix-1]:
       return False
  return True

下面是一个有趣的解决方案,它使用for循环逐个字符进行检查

def ispal(word):
    try:
        for c in word:
            if word[0] != word[-1]:
                return False
            word = word[1:-1]
    except IndexError:
        return True
如果需要,您可以添加更奇特的内容,例如大小写或标点符号不敏感

作为无for循环的递归解决方案,它更简单:

def ispal(word):
    if word:
        return word[0] == word[-1] and ispal(word[1:-1])
    return True

所以,等等。这需要找出它是否仅仅是基于字符的回文?我们可以去掉标点、空格等等?
Sarip | Paris!
在逻辑上不是回文,因为
,我们只是看字母,比如
saripparis
?顺便说一句,我讨厌这样的作业。这应该是两行的而不是一个大的长赋值。
def checkPalindrome(word):返回word==word[:-1]
adsmith:我完全同意你的看法。jwarner112:Sirap,我是Paris!程序应该成功地将其视为回文,因为我们必须排除像、和这样的字符。我想这只是为了让作业更复杂一点。而不是word=word。替换(每个“”)您可以完全避免循环,并按照示例使用word.strip(标点符号)。我相信它只会从字符串中删除标点符号中的任何字符。哦,好主意!让我编辑一下……我已经使用了“”。strip()但出于某种原因,我从来没有想过将其用于除空格剥离以外的任何操作!请记住,剥离仅用于修剪字符串的开头和结尾。它不会删除第一个和最后一个有效字符之间的任何内容。@Ffisegydd仔细检查,这是行不通的。我确信有比我的<代码>更好的方法来完成此操作>对于loop,但是str.strip()只删除前导字符和尾随字符。不过正则表达式速度很慢。如果不是OP的老师把这个问题与尝试教循环混淆在一起的话,试图避免在一些本应该是简单的单行程序中使用它们;PHi Joachim(我也是瑞典人,但我会用英语)您的for循环代码段,我是否应该将x切换到word?(即if word.isalpha()中的word.upper()等)。如果不是,x来自何处?修复了它,谢谢!缩进没有正确粘贴。
def ispal(word):
    if word:
        return word[0] == word[-1] and ispal(word[1:-1])
    return True