快速和pythonic方式来确定anagram是否是回文?

gar*_*lfd 1 python

给定一个字符串,我们如何检查它的任何字谜是否可以作为回文?

例如,让我们考虑字符串"AAC".它的字谜是"ACA",它是一个回文.如果我们可以从给定字符串的任何anagram形成回文,我们必须编写一个接受字符串并输出true的方法.否则输出错误.

这是我目前的解决方案:

from collections import defaultdict

def check(s):
    newdict = defaultdict(int)
    for e in s:
        newdict[e] += 1
    times = 0
    for e in newdict.values():
        if times == 2:
            return False
        if e == 1:
            times += 1
    return True
Run Code Online (Sandbox Code Playgroud)

使用python库的任何更短的解决方案?

Eri*_*got 5

这是使用标准库的更短的解决方案,具有更正的算法(所有字符计数必须是偶数,除了最多一个):

from collections import Counter
def check(s):
    return sum(1 for count in Counter(s).itervalues() if count % 2 == 1) <= 1
Run Code Online (Sandbox Code Playgroud)

这很短但很"慢",因为程序会经历所有奇数计数而不是在找到两个计数后立即停止.一个尽快停止的更快的解决方案是:

def check(s):
    odd_counts = (count for count in Counter(s).itervalues() if count % 2 == 1)
    try:
        next(odd_counts)  # Fails if there is no odd count
        next(odd_counts)  # Fails if there is one odd count
    except StopIteration:
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)