gpt4 book ai didi

python - 快速和 pythonic 的方法来找出一个字谜是否是回文?

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:38 25 4
gpt4 key购买 nike

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

例如让我们考虑字符串“AAC”。它的一个变位词是“ACA”,它是一个回文。如果我们可以从给定字符串的任何变位词形成回文,我们必须编写一个方法,该方法接受一个字符串并输出 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

有没有使用 python 库的更短的解决方案?

最佳答案

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

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

这很短但很“慢”,因为程序会遍历所有奇数计数,而不是一找到两个就停止。尽快停止的更快的解决方案是:

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

关于python - 快速和 pythonic 的方法来找出一个字谜是否是回文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22656764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com