gpt4 book ai didi

python - 比较字符串中字符的出现次数

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

code

def jottoScore(s1,s2):

n = len(s1)

score = 0

sorteds1 = ''.join(sorted(s1))

sorteds2 = ''.join(sorted(s2))

if sorteds1 == sorteds2:
return n

if(sorteds1[0] == sorteds2[0]):
score = 1
if(sorteds2[1] == sorteds2[1]):
score = 2
if(sorteds2[2] == sorteds2[2]):
score = 3
if(sorteds2[3] == sorteds2[3]):
score = 4
if(sorteds2[4] == sorteds2[4]):
score = 5

return score


print jottoScore('cat', 'mattress')

我正在尝试编写一个 jottoScore 函数,它将接收两个字符串并返回两个字符串之间共享的字符出现次数。

I.E jottoScore('maat','caat') 应该返回 3,因为有两个 A 被共享,一个 T 被共享。

我觉得这是一个足够简单的独立练习题,但我不知道如何遍历字符串并比较每个字符(我已经按字母顺序对字符串进行了排序)。

最佳答案

如果您使用的是 Python2.7+,那么我会采用以下方法:

from collections import Counter

def jotto_score(str1, str2):
count1 = Counter(str1)
count2 = Counter(str2)
return sum(min(v, count2.get(k, 0)) for k, v in count1.items())

print jotto_score("caat", "maat")
print jotto_score("bigzeewig", "ringzbuz")

输出

3
4

关于python - 比较字符串中字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073651/

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