-1

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!"

  • why do you have that `if` statement? it is kind of pointless, all it does is make the function return `None` if there are no spaces, also you don't need to go over each character individually, just check if the reversed string is equal – Matiiss Mar 17 '22 at 12:16
  • 1) `palindrome=reversed(words)` don't belong in the if condition. If the word has no spaces your variable palindrome won't be defined. 2) why you loop through the letters of the word ? if it is a palindrom you just need to compare words and palindrome to be equal? (and even if you do it that way, I don't get what `if len(words)==1` is supposed to do ? – Rabinzel Mar 17 '22 at 12:25
  • The main point is that `sys.argv[1]` takes the 1st argument, so if you write your argument without quotes and that it contains a space, it will count as 2 args. See the 1st part of my answer. – Titouan L Mar 17 '22 at 12:26

4 Answers4

0

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 code example is that among every non alphabetic caracters you are only trying to handle the space.

def palindrome(words):
    words = ''.join(filter(str.isalnum, words.lower()))

    palindrome = words[::-1]
    if palindrome == words:
            return ("It's a palindrome!")
    return ("It's not a palindrome!")


print(palindrome(sys.argv[1]))
Titouan L
  • 1,182
  • 1
  • 8
  • 24
  • 1
    you don't need to explicitly check if there is a space in `words`, `replace` won't throw an error if there won't be, also there is no need to iterate over the reversed word, just `join` it and compare both words – Matiiss Mar 17 '22 at 12:22
  • I know, but I tried to write a relatively similar structure for him to compare with his code, maybe this is a minimal reproductible example and theres more going on. But I totaly agree with you ! – Titouan L Mar 17 '22 at 12:23
  • @TitouanL The question states "...consider only the alphanumeric characters in the string". While your solution works for the sample data it does not comply with this essential requisite as you're only removing commas and spaces. Even so, bizarrely, it's been accepted as the definitive answer – DarkKnight Mar 17 '22 at 16:31
  • @ArthurKing yeah, the question has been revised a lot of times since I posted my 1st answer, and I did not change it everytime. Since a lot was going on in the comments and that SmittySmerk deleted all his comments, I updated my answer with the complete solution. – Titouan L Mar 18 '22 at 08:07
  • 2
    @TitouanL Should be *str.isalnum* to comply with the OP's requirements – DarkKnight Mar 18 '22 at 08:45
0

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 ')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

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!
Emmanuel
  • 245
  • 2
  • 5
  • The function works fine just make the necessary changes to fit how you want to use it; ie. with command line arguments. – Emmanuel Mar 17 '22 at 13:23
0
    String original = "rA89293cEC@Ar";
           original = original.replaceAll("[^a-zA-Z]","").toLowerCase();
    String originalReverse = new StringBuilder(original).reverse().toString();

    System.out.println(original.equals(originalReverse));
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 28 '22 at 07:48