Python 2.7.6:使用for循环制作回文检查器

时间:2013-12-13 16:24:28

标签: python palindrome

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

我一直试图评论我写过的想法。我在Python中做的很少,并且是一个非常新的初学者,所以如果回复请记住。

提前谢谢你!

(这段代码在18上获得了一个运行错误代码,我想知道为什么,我想知道是否有人对如何获得代码有任何想法1)工作2)更简约,我觉得我已经过度了整个事情?)

# -*- coding: UTF-8 -*-
# Python 2.7.6

print 'Welcome to the most unfunctional palindrome-checker you can find'

def main():
    global word
    word = raw_input('Type the word that you want to check:\n ').lower()
    forwards = word
    backwards = word[::-1] # reverses the input so we can compare them later
    remove = (",", ":", ".", "=", "!", "?") # does this remove these characters from the input?
    replaceDict = {"3":"e", "0":"o", "1":"i"} # does this replace 3, 0, 1
    # with e, o i? (defined in next function)

""" here I'm trying to build the for-loop (that i must use for this assignment)
that changes 3:e, 0:o, 1:i, and removes ,:.=!? from "forwards", so we can just use
backwards to compare them later in the function "result"     
"""
    for char in word:
        if char in replaceDict:
            replaceChar(char, replaceDict[char])
        elif char in remove:
            replaceChar(char, "")
    return    

def replaceChar(char, replace):
    global forwards
    forwards.forwards.replace(char, replace)

def result(forwards):
    for i in range(0, len(forwards)):
        if forwards[i] != backwards[i]:
            print "Not a palindrome."
            return

    print "Yes, that is a palindrome!"


main()

4 个答案:

答案 0 :(得分:2)

不是循环,但使用理解相当简单;

def ispalindrome(a):
  a1 = [x.upper() for x in a if x.isalpha()]
  return a1 == a1[::-1]

如果你真的需要一个for循环,你可以用更复杂的东西替换简单的return;

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

答案 1 :(得分:0)

这是我最好的选择。

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

答案 2 :(得分:0)

使用循环执行此操作的最简单方法是利用python负索引从序列右侧开始计算的事实。因此,你想做:

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

显然,你可以提高效率(现在每次检查两次)。

答案 3 :(得分:0)

这是一个有趣的解决方案,使用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