Search code examples
pythonpalindrome

Palindrome words check function : python 3


The is_palindrome function checks if a string is a palindrome. A palindrome is a string that can be equally read from left to right or right to left, omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". Fill in the blanks in this function to return True if the passed string is a palindrome, False if not.

def is_palindrome(input_string):
    # We'll create two strings, to compare them
    new_string = ""
    reverse_string = ""
    # Traverse through each letter of the input string
    for letter in input_string:
        # Add any non-blank letters to the 
        # end of one string, and to the front
        # of the other string. 
        if letter != " ":
            new_string     += letter
            reverse_string = letter + reverse_string
    return new_string
    # Compare the strings
    if new_string.lower() == reverse_string.lower():
        return True
    return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True

Solution

  • There are a few issues:

    • The y variable should start at -1, since it should reference the last character.
    • The incremental change to y is not correctly indented, as it should be part of the for loop
    • input_string[y] was a good idea, but you need a separate if condition for checking whether that character is a non-blank
    • There is a return new_string statement that should not be there, since the final if still needs to be executed

    I should also note that this template code is very restrictive and is not promoting a pythonic coding style, but here are the corrections for the above issues:

    def is_palindrome(input_string):
        new_string = ""
        reverse_string = ""
        y = -1  # must be -1 not 1
        for letter in input_string:
            if letter != " ":
                new_string     += letter
            if input_string[y] != " ":   # separate condition
                reverse_string += input_string[y]
            y -= 1  # fixed indentation
        
        if new_string.lower() == reverse_string.lower():  # added condition
            return True
        return False
    

    Again, this is not the most elegant solution, nor is it very efficient.