How to check if permutation of a string is a palindrome

check if string contains palindrome
palindrome permutation c
make palindrome from string
palindrome permutation lintcode
write a code to find whether any permutation of a given string can form a palindrome
given a string, determine whether any permutation of it is a palindrome recursion
generate palindromes
palindrome using hashmap

Im new to python and im trying to check if any permutation of a string is a palindrome. Here is my code:

def isPal(s):
    a = set()
    for i in s:
        if i in a:
            a.remove(i)
        else:
            if (i != '\n') or (i != ' '):
                a.add(i)
    if len(a) <= 1:
        print(s + ' is a palindrome permutation\n')
    else:
        print(s + ' is not a palindrome permutation\n')
     print(a)

The problem I am having is that it I dont want my set to include spaces or any puncuation thats in the string. Is there any way to only check the letters? For example, the string "Mr. owl ate my Metal worm" shouldnt use the period or spaces when checking if it is a palindrome.

You can certainly check all permutations, but there is a much more efficient approach.

Note that in order for a string to be a palindrome, then every letter is mirrored around the center of the string. That means a collection of letters can form a palindrome if there is at most one letter that has an odd count.

Here is how you can implement this:

The first step is to convert the string to lower case and remove the nonalpha characters (like spaces and punctuation). We can do that by using a list comprehension to iterate over each character in the string and keep only those where str.isalpha() returns True.

myString = "Mr. owl ate my Metal worm"
alpha_chars_only = [x for x in myString.lower() if x.isalpha()]
print(alpha_chars_only)
#['m', 'r', 'o', 'w', 'l', 'a', 't', 'e', 'm', 'y', 'm', 'e', 't', 'a', 'l', 'w', 'o', 'r', 'm']

Next count each letter. You can use collections.Counter for this:

from collections import Counter 
counts = Counter(alpha_chars_only)
print(counts)
#Counter({'m': 4, 'a': 2, 'e': 2, 'l': 2, 'o': 2, 'r': 2, 't': 2, 'w': 2, 'y': 1})

Finally count the number of letters that have an odd count. If the count is 0 or 1, a palindrome must be possible.

number_of_odd = sum(1 for letter, cnt in counts.items() if cnt%2)
print(number_of_odd)
#1

Putting that all together, you can make a function:

def any_palindrome(myString):
    alpha_chars_only = [x for x in myString.lower() if x.isalpha()]
    counts = Counter(alpha_chars_only)
    number_of_odd = sum(1 for letter, cnt in counts.items() if cnt%2)
    return number_of_odd <= 1

print(any_palindrome(mystring))
#True

Check if characters of a given string can be rearranged to form a , You can certainly check all permutations, but there is a much more efficient approach. Note that in order for a string to be a palindrome, then every letter is  Basically, a palindrome has to have maximum of one odd letter (the middle one). So basically the function checks if the letter in string is dividable by 2, if it's not then it's incrementing odd letter counter. Then if the odd counter is higher then 1 it's going to return False, meaning that that string cannot be a permutation of palindrome.

Palindrome Permutation, In this video, we will be considering how to determine if a string is a palindrome permutation Duration: 11:59 Posted: Mar 26, 2018 Now for each permutation of the string (which will forms left half of palindrome), we can easily construct the right half by reversing the left half. If the string contains one odd occurring element, all palindromic permutations will be of odd length with mid element equal to odd occurring character.

I think you can just do something like this:

from string import ascii_letters
from collections import Counter
s = "Mr. owl ate my Metal worm"

def is_permutation_palindrome(s):
 return len([i for i in Counter(c.lower() for c in s if c in ascii_letters).values() if i&1]) < 2

print(is_permutation_palindrome(s))

You have a Counter structure that keeps the count of the lowercase version of each letter and you simply return True if the number of letters with an odd count is 1 or less.

Here is a less compressed version of the code that should be easier to understand and doesnt use any imports:

s = "Mr. owl ate my Metal worm"
def is_permutation_palindrome(s):
    counts = {}
    for c in s.lower():
        if c.isalpha():
            if c in counts:
                counts[c] += 1
            else:
                counts[c] = 1

    odd_counts = [count for count in counts.values() if count % 2 == 1]
    return len(odd_counts) < 2

How to check if permutation of a string is a palindrome, Learn how to check if a string is a permutation of a palindrome in O(N) time, where N is the Duration: 5:35 Posted: Dec 15, 2018 We traverse over the string s s s and put in the number of occurences of each character in this m a p map m a p appropriately as done in the last case. Later on, we find the number of characters with odd number of occurences to determine if a palindromic permutation is possible for the string s s s or not as done in previous approaches.

I though of a very simple function to check if it's a permutation of a palindrome. Basically, a palindrome has to have maximum of one odd letter (the middle one). So basically the function checks if the letter in string is dividable by 2, if it's not then it's incrementing odd letter counter. Then if the odd counter is higher then 1 it's going to return False, meaning that that string cannot be a permutation of palindrome.

def is_palindrome(s):
    odd_counter = 0
    for letter in s:
        if s.count(letter) % 2 != 0:
            odd_counter += 1

    if odd_counter > 1:
        return False
    return True

String Processing in Python: Is Palindrome Permutation, Check whether letters of string can make a palindrome or not, if it can`t form a palindrome return. a. Initialize count array with zeroes. b. Fill with the frequency with  from collections import Counter def is_palindrome_permutation(data: str) -> bool: """Given a string, check if it is a permutation of a palindrome.""" data = data.lower().replace(' ', '') num_odd = sum(1 for char, freq in Counter(data).items() if char != ' ' and freq % 2 == 1) # Check for two types of palindromes , 1) Odd Length (e.g. abc cba) 2

All we need to look for is a character with odd frequency, in this case, using a counter object is very useful instead of calculating the count the frequency of each character in the string we can have a counter object for the string with the frequency for every character in the string. From the values of the counter object, we can determine if more than one character with an odd frequency which makes the string not possible to be a palindrome.

from collections import Counter

def permutationPalindrome(string):
    counterObject = Counter(char for char in string.lower() if char.isalpha())
    no_of_odd = 0
    for value in counterObject.values():
        if value % 2 != 0:
            no_of_odd += 1
        if(no_of_odd > 1):
            return False
    return True

Coding Interview Tutorial 20: Palindrome Permutation [LeetCode , We know that the left and right half of a palindrome contains same set of characters, so any palindromic permutations of a string is only possible if the frequency  A String is called Palindrome if it reads the same backwards as well as forwards. For example, the String a b a can be read the same backwards as well as forwards. Now, a Permutation of a String S is some String K where S and K contain the same set of characters, however, these characters need not necessarily have the same positions.

Palindrome permutations of a string, Some suggestions: You strip out spaces, then on the next line check if each character is a space. The second part is redundant. The only  Check if the characters in a string form a Palindrome in O (1) extra space Check if string can be rearranged so that every Odd length Substring is Palindrome Find the count of sub-strings whose characters can be rearranged to form the given word Check if string remains palindrome after removing given number of characters

Find all palindromic permutations of a string, A String is called Palindrome if it reads the same backwards as well as forwards. need to find out whether any permutation of this given String is a Palindrome. You should find a permutation P of numbers 1 through n such that if you apply this permutation on the string s, you will get a palindromic string. The result of applying a permutation P on the string s is a string t with length n such that for each i (1 ≤ i ≤ n ), the i -th character of t is given as as t [ i ] = s [ P i ].

Check if a string is a permutation of a palindrome using Python , After above checking we can make half part of first palindrome string (lexicographically smallest) by taking half frequency of each letter of the given string. Now traverse through all possible permutation of this half string and each time add reverse of this part at the end and add odd frequency character in mid between if string is of odd length, for making the palindrome.

Comments
  • Can't you just check the counts of each letter? If at most 1 has an odd count, then a palindrome must exist. Seems better than checking all permutations.
  • import re regex = re.compile('[^a-zA-Z]') def is_pal(string): # Remove non-letters regex.sub('', string) # Return True if string is equal to itself backwards. return string == string[::-1]
  • @Prune the question wasn't whether a string is a palindrome or not, but whether it has a permutation that is.
  • I think this might have been closed prematurely. I believe the question is does any permutation exist, not is this exact string palendromic. paults solution will work if that's the case. You can use collections.Counter to count the letters.
  • Do look at the collections module, type Counter. @pault has already given you the algorithm; I'm hopeful of seeing that posted as an answer, any minute now. The existing answer is a clone thereof.
  • Head-slap! I intended to write it that way, but was coding a "count the evens" expression in my interleaved task.
  • you dont need to use a list comprehension inside the counter. You can see in my solution that a generator will work fine. You can also get rid of the letter,cnt and just use the Counter.values() instead to get a list of counts only.
  • @GrantWilliams Thanks; refinements that I missed.
  • I wrote it as a one liner because i was planning on posting it in the comments, but you can easily make it a little more readable too.
  • What insight does this add to, say, Prune's answer the day the question was asked?