简体   繁体   中英

Python 2.7.6: Making a palindrome checker with a for-loop

I'm doing a palindromechecker that is required to have a for-loop inbuilt that checks the word character by character, because the palindrome checker must work even if you use dots, lower/uppercase letters etc. For example: Sirap I Paris! must work to write.

I've been trying to comment on the lines that I've written what my thought is. I've done very few stuff in Python and are a really new beginner, so please bear in mind if replying.

Thank you alot in advance!

(This code gets a run error code on 18, I wonder why and I wonder if anyone has any ideas on how to get the code 1) working 2) more minimalistic, I feel I've overdone the whole thing?)

# -*- 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()

No for loop, but fairly simplistic using comprehensions;

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

If you really need a for loop, you can replace the simlpe return with the a bit more complex;

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

Here's my best go at it.

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

The simplest way to do this with a loop is to exploit the fact that python negative indexes are counted from the right of a sequence. Thus, you want to do:

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

Obviously, you can make this more efficient (right now this checks every pair twice).

Here is an interesting solution using a for-loop that checks character by character.

def ispal(word):
    try:
        for c in word:
            if word[0] != word[-1]:
                return False
            word = word[1:-1]
    except IndexError:
        return True

You can add fancier things such as case or punctuation insensitivity if needed.

It is simpler as a recursive solution without the for loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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