words = ['Anna', 'Alexey', 'Alla', 'Kazak', 'Dom']
def palindrome():
filtered_2 = list(filter(lambda x: x == x[::-1], words))
print(filtered_2)
palindrome()
The code should return palindrome words, but it gives me an output like this:
[]
It should give:
['Anna', 'Alla', 'Kazak']
CodePudding user response:
You need to normalize the input before comparisons. Basically you are checking if 'A' == 'a'
which will fail.
Try this example where I normalize to lowercase using str.lower()
:
words = ['Anna', 'alexey', 'Alla', 'kazak', 'dom']
def palindrome():
filtered_2 = list(filter(lambda x: x.lower() == x.lower()[::-1], words))
print(filtered_2)
palindrome()
CodePudding user response:
If using Python >= 3.8, it is possible to use the walrus operator (:=
) to keep the original words in the result and have only one .lower()
call per word:
filtered_2 = [x for x in words if (y := x.lower()) == y[::-1]]
CodePudding user response:
Let me also highlight the fact that the definition of the function palindrome
as in your code is pointless and the script would work exactly the same without defining the function:
words = ['Anna', 'alexey', 'Alla', 'kazak', 'dom']
_words=map(str.lower,words)
filtered_2 = list(filter(lambda x: x == x[::-1], _words))
print(filtered_2)
But if you want to make it with a function this is the simples way:
def palindrome(words_list):
_words=map(str.lower,words)
filtered = list(filter(lambda x: x.lower() == x.lower()[::-1], words))
return filtered
In this way this code
words = ['Anna', 'Alexey', 'Alla', 'Kazak', 'Dom']
palindrome(words)
would return the results you want.