-1

I have created a very simple palindrome checker with doctests.

I'm having problem with the last doctest. It fails and is not carrying out the ignorecase=True. I cannot work out why the last test is failing.

Code:

# This Python file uses the following encoding: utf-8
def isPalindrome(s, ignorecase=False):
    """
    >>> type(isPalindrome("bob"))
    <type 'bool'>
    >>> isPalindrome("abc")
    False
    >>> isPalindrome("bob")
    True
    >>> isPalindrome("a man a plan a canal, panama")
    True
    >>> isPalindrome("A man a plan a canal, Panama")
    False
    >>> isPalindrome("A man a plan a canal, Panama", ignorecase=True)
    True
    """

    # Create an empty string "onlyLetters"
    # Loop over all characters in the string argument, and add each 
    #   character which is a letter to "onlyletters"

    # Reverse "onlyletters" and test if this is equal to "onlyletters"

    #s = ""
    news = ""
    for eachLetter in s:
        if eachLetter.isalpha():
            news += eachLetter
    #print news

    onlyLetters = news
    #print onlyLetters   

    onlyletters = news[::-1]
    #print onlyletters

    if onlyLetters == onlyletters:
        return True
    else:
        return False
4

3 に答える 3

3

私はあなたの変数の選択が嫌いであることに注意してください。onlylettersの逆ですonlyLetters、ええ、明らかに... とにかく。

あなたはignorecaseそれをどのように機能させることができますか?

考えられる解決策は次のとおりです。

if ignorecase:
    return onlyLetters.lower() == onlyletters.lower()
else:
    return onlyLetters == onlyletters
于 2013-11-13T12:33:04.047 に答える