mothinx
mothinx

Reputation: 45

How to improve my code from codefights - palindromeRearranging

I'm looking for advices to improve this code submitted on CodeFight. Actually it's working well but i know it could be improved.

The goal of the function is to find out if a string can be rearranged to form a palindrome. I took the problem as a simple problem: any letter has to be divided by 2 except if the string is odd. In this case, all letters except 1 has to be divided by 2.

def palindromeRearranging(inputString):

i = 0
count = 0
# a count to know how many char cant be 
# divided by 2. used only for odd strings

if len(inputString) % 2 == 0:
    # if len is pair
    # every char counts has to be divided by 2
    for letter in inputString:
        if inputString.count(letter) % 2 != 0:
            return False

elif len(inputString) == 1:
    # if there is only one char
    # string is palindrome
    return True

elif len(inputString) % 2 != 0:
    # if len is odd
    # every char counts has to be divided by 2
    # except for 1 char
    for letter in inputString:
        if inputString.count(letter) % 2 != 0:
            count += 1      
    if count > 1:
        return False

return True

Is there a better way to write my solution ? Thanks mentors !

Upvotes: 0

Views: 986

Answers (1)

Maharramoff
Maharramoff

Reputation: 1021

Try this approach

from collections import Counter

def palindromeRearranging(s):
    return sum(i % 2 == 1 for i in Counter(s).values()) <= 1

Upvotes: 1

Related Questions