So 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 ___:
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if ___:
new_string = ___
reverse_string = ___
# Compare the strings
if ___:
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
CodePudding user response:
We are removing any whitespace and uppercasing the string to make sure there are no issues.
Then, using slice notation, we compare the original string with itself, but reversed.
def is_palindrome(input_string):
new_string = input_string.upper()
new_string = new_string.replace(" ", "")
return new_string == new_string[::-1]
print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
Outputs:
True
False
True
CodePudding user response:
Here is how you can solve your exercise:
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 c in input_string:
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if c != '':
new_string = new_string c
reverse_string = c reverse_string
# Compare the strings
if new_string == reverse_string:
return True
return False