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
There are a few issues:
y
variable should start at -1, since it should reference the last character.y
is not correctly indented, as it should be part of the for
loopinput_string[y]
was a good idea, but you need a separate if
condition for checking whether that character is a non-blankreturn new_string
statement that should not be there, since the final if
still needs to be executedI 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.