-1

Hi i'm trying to achieve this output. I'm trying to see if the string is a palindrome by comparing the first word and the last word, second word and the second last word.

King, are you glad you are king is a palindrome (or that's the outcome i'm trying to achieve) as the 1st word is similar to the last word (which is king), the second word is similar to the second last word (which is are), the third word is similar to the third last word (which is you). hence, the output should be true. (this is the requirement of my assignment)

Output i'm trying to achieve: [True, False] Output i got: [False]

3 Answers3

3

You need to do split in order to word-wise comparison.

In addition, take out ' ' from bad_character and fixing some indentation will do:

def palindrome_word(a_str):
    outputlist = []
    bad_character = ['?', ',']
    for element in a_str:
        for words in bad_character:
            element = element.replace(words, '')
        element = element.lower().split()
        outputlist.append(element == element[::-1])
    return outputlist

Or using re:

import re

def palindrome_word_re(a_str):
    outputlist = []
    for element in a_str:
        element = element.lower()
        words = re.findall('\w+', element)
        outputlist.append(words == words[::-1])
    return outputlist

Both outputs:

palindrome_word(my_string)
palindrome_word_re(my_string)

[True, False]
Chris
  • 29,127
  • 3
  • 28
  • 51
0

Here is a solution

def palindrome_word(a_str):
    outputlist = []
    bad_character = ['?', ',']
    for element in a_str:
        for words in bad_character:
            element = element.replace(words, '')
        element = element.lower()
        result = (element.split())[::-1] == element.split()
        outputlist.append(result)
    return outputlist

my_string=["King, are you glad you are king?", "Hello Bye"]
print(palindrome_word(my_string))

OUTOUT

[True, False]
MasterOfTheHouse
  • 1,164
  • 1
  • 14
  • 34
0

Another approach -

def palindrome_word(a_str):
    import re
    outputlist = []
    for element in a_str:
        str_arr = re.findall('\w+', element.lower())
        is_palindrome = True
        for i in range(int(len(str_arr)/2)):
            if str_arr[i] != str_arr[-i-1]:
                is_palindrome = False
                break
        outputlist.append(is_palindrome)
    return outputlist

my_string=["King, are you glad you are king?", "Hello Bye"]
print(palindrome_word(my_string))

Output

[True, False]
som
  • 71
  • 4