Create a program, palindrome.py, that has a function that takes in one string argument and prints a sentence indicating if the text is a palindrome. The function should consider only the alphanumeric characters in the string, and not depend on capitalization, punctuation, or whitespace. If the string is a palindrome, it should print: It's a palindrome! However, if the string is not a palindrome, it should print: It's not a palindrome!
The Problem
My code is not printing whether it is a palindrome when there are spaces inside the string, but does print that it is not a palindrome despite having spaces. I included replace(), zip(), and reversed() in my code to account for the spaces and the reversed words, but it is not printing the desired result.
What am I missing or doing wrong in my code?
import sys
def palindrome(words):
if ' ' in words:
palindromes = words[::-1]
if palindromes == words:
return "It's a palindrome!"
return "It's not a palindrome!"
print(palindrome(sys.argv[1]))
Example Test Cases
Test Case 1
tests 1 Run python3 palindrome.py 'Dennis, Nell, Edna, Leon, Nedra, Anita, Rolf, Nora, Alice, Carol, Leo, Jane, Reed, Dena, Dale, Basil, Rae, Penny, Lana, Dave, Denny, Lena, Ida, Bernadette, Ben, Ray, Lila, Nina, Jo, Ira, Mara, Sara, Mario, Jan, Ina, Lily, Arne, Bette, Dan, Reba, Diane, Lynn, Ed, Eva, Dana, Lynne, Pearl, Isabel, Ada, Ned, Dee, Rena, Joel, Lora, Cecil, Aaron, Flora, Tina, Arden, Noel, and Ellen sinned' and match its output to an expected value.
Test Case 2
test 2 Run python3 palindrome.py 'Ed, I saw Harpo Marx ram Oprah W. aside' and match its output to an expected value.
Outputs
Expected Output: "It's a palindrome!"
Actual Output: "It's not a palindrome!"
CodePudding user response:
I'm unsure what your code tries to achieve. But I can see you try to check if word has a length of one, since that would automatically be a palindrome. That code should go outside for the loop. It could be at the beginning of your function. What you should be doing inside the for loop is comparing the characters in words and palindrome. But even that is going to fail if words contains punctuations since those are not being considered in this problem. I would advise you remove all spaces and punctuations and make sure all characters are lower case or they are all upper case (so that your function can be capitalisation blind). Then you can compare the characters in words and palindrome, where you return False as soon as you find unequal characters or return True if no unequal characters are found.
I however find that process long so below is a simpler solution I made (which solves the problem fully):
def palindrome(words):
new_word = ""
'''
Collect alpha numeric characters into new_word
Spaces are removed and all characters are changed to lower case
so that capitalisation can be ignored
'''
for char in words.replace(" ", "").lower():
if char.isalnum():
new_word = char
# Check if word is a palindrome
if list(new_word) == list(reversed(new_word)):
print("It's a palindrome!")
else:
print("It's not a palindrome")
test:
palindrome('Dennis, Nell, Edna, Leon, Nedra, Anita, Rolf, Nora, Alice, Carol, Leo, Jane, Reed, Dena, Dale, Basil, Rae, Penny, Lana, Dave, Denny, Lena, Ida, Bernadette, Ben, Ray, Lila, Nina, Jo, Ira, Mara, Sara, Mario, Jan, Ina, Lily, Arne, Bette, Dan, Reba, Diane, Lynn, Ed, Eva, Dana, Lynne, Pearl, Isabel, Ada, Ned, Dee, Rena, Joel, Lora, Cecil, Aaron, Flora, Tina, Arden, Noel, and Ellen sinned')
Output: It's a palindrome!
CodePudding user response:
Your whole code is indented in the first if
condition, which means it would work only if your entry string has a space in it.
On top of that, do you use quotes or double quotes when you add your argument ? Because using sys.argv[1]
takes the 1st argument.
python3 palindrome.py hey yeh # does not work
python3 palindrome.py "hey yeh" # is supposed to work
The probleme with your sample data is the ,
...
def palindrome(words):
words = words.lower() # Lower case for comparison purpose
words = words.replace(' ', '')
words = words.replace(',', '')
palindrome = words[::-1]
if palindrome == words:
return ("It's a palindrome!")
return ("It's not a palindrome!")
print(palindrome(sys.argv[1]))
CodePudding user response:
Bear in mind that replace replaces all occurrences of the given pattern. No real need to check if there are spaces in the word - just do it unconditionally.
Even better, use a regular expression to eliminate the whitespace and punctuation.
import re
def palindrome(s):
s = re.sub('[^\w]', '', s.lower())
return "It's a palindrome" if s == s[::-1] else "It's not a palindrome"
If you don't want to import re then:
def palindrome(s):
s = ''.join(c for c in s.lower() if c.isalnum())
return "It's {}a palindrome".format('' if s == s[::-1] else 'not ')
...and if you're into one-liners:
def palindrome(s):
return "It's {}a palindrome".format('' if (s := ''.join(c for c in s.lower() if c.isalnum())) == s[::-1] else 'not ')