Checking if any permutation of a string can make it palindrome

I was writing code to check if any permutation of a string can make it palindrome and came up with the following logic:

anagram = [ x for x in input() ]
count_alphabets = [ anagram.count(x) for x in set(anagram) ]
middle_element = [x for x in count_alphabets if x % 2 == 1]
print("YES") if len(middle_element) == 0 or len(middle_element) == 1 else print("NO")


The logic is to count the number of times each character appears. ONLY one or none of the characters can appear odd number of times.

The above logic works fine and passes all test cases. Is there a better logic for this?

1 Answer

You may simply use Counter method of collections module to get the frequency of each character in the given word and then simply create a list of the frequency of a given character modulo 2, and then get the sum of the generated list, So the list will have only 2 values, either 0 or 1, So we calculate the sum of the list, and evaluate the condition of <=1 is True

from collections import Counter

s = "summs"

print sum([i%2 for i in Counter(s).values()]) <= 1