سؤال

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
هل كانت مفيدة؟

المحلول

Note that I hate your variable choices. onlyletters is the reverse of onlyLetters, yeah, obviously... Anyway.

You don't use ignorecase so how could it work?

Here's a possible solution:

if ignorecase:
    return onlyLetters.lower() == onlyletters.lower()
else:
    return onlyLetters == onlyletters

نصائح أخرى

My 2¢ solution:

def is_palindrome(s):
    if s == '':
        return True
    else:
        if s[0] == s[-1]:
            return is_palindrome(s[1:-1])
        else:
            return False

The output:

print is_palindrome('')
#>>> True 
print is_palindrome('abab')
#>>> False 
print is_palindrome('abba')
#>>> True

My solution would be to substitute any non-letter with nothing, after lowering the case.

import re
def isPalindrome(s, ignoreCase):
    if ignoreCase: 
       s = s.lower()
    onlyLetters = re.sub("[^a-z]+", "", s)
    return(onlyLetters == onlyLetters[::-1])
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top