如何通过 codefights - palindromeRearranging 改进我的代码

How to improve my code from codefights - palindromeRearranging

我正在寻找建议来改进在 CodeFight 上提交的代码。实际上它运行良好,但我知道它可以改进。

该函数的目标是找出字符串是否可以重新排列以形成回文。我把这个问题当作一个简单的问题:任何字母都必须除以 2,除非字符串是奇数。在这种情况下,除 1 以外的所有字母都必须除以 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

有没有更好的方法来编写我的解决方案?感谢导师!

试试这个方法

from collections import Counter

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