计算字符串Python中的常用字符

时间:2017-05-30 18:28:58

标签: python count set intersection

此代码的输出仍为4.然而,输出应为3.设置交集存在,因为我认为这是答案的关键。答案为4而不是3的推理来自s q中与s2匹配的2 qs和1 r的数量。

s2 = "qsrqq"
s1 = "qqtrr"
counts1=0
counts2=0
letters= set.intersection(set(s1), set(s2))
for letter1 in set(s1):
    counts1 += s2.count(letter1)
for letter2 in set(s2):
    counts2 += s1.count(letter2)


counts = min(counts1, counts2)
print (counts)

非常感谢任何帮助。

8 个答案:

答案 0 :(得分:5)

如果您想保持共同字符数的计数,则应使用collections.Counter代替set

from collections import Counter

s2 = 'qsrqq' 
s1 = 'qqtrr'

common_letters = Counter(s1) & Counter(s2)  # => {'q': 2, 'r': 1}
print(sum(common_letters.values()))         # => 3

答案 1 :(得分:1)

我替换了你原来的代码块

for letter1 in set(s1):
    counts1 += s2.count(letter1)

为:

for letter1 in set(s1):
    v = s2.count(letter1)
    print("{0}:{1}".format(letter1, v))
    counts1 += v

输出,它是具有出现次数的字母:

r:1
q:3
t:0

这是正确的,字符串s2是qsrqq,你检查set(s1),其中包含rq 计数是正确的。同样,如果检查第二个for循环,则输出为:

q:3
r:1
s:1

因此最小计数为4。

答案 2 :(得分:1)

这是一个不涉及集合的解决方案:

s2 = sorted("qsrqq")
s1 = sorted("qqtrr")

count = 0
while len(s1)>0 and len(s2)>0:
    if s1[0] == s2[0]:
        count += 1
        s1 = s1[1:]
        s2 = s2[1:]
    elif s1[0] < s2[0]:
        s1 = s1[1:]
    else:
        s2 = s2[1:]

print(count)

答案 3 :(得分:1)

这是使用无模块的另一种方法。

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(null, null, null);
    SSLContext.setDefault(sslContext);

答案 4 :(得分:1)

#!/usr/bin/python
s2 = "qsrqq"
s1 = "qqtrr"
counts1=0
counts2=0
letters= set.intersection(set(s1), set(s2))
print ("letters: "+str(letters) + " intersection count: "+str(len(letters)))
for letter1 in set(s1):
    print ("letter1 " + str(letter1))
    counts1 += 1
for letter2 in set(s2):
    print ("letter2 " + str(letter2) )
    counts2 += 1

print ("counts1 " + str(counts1) + " counts2 " + str(counts2) )
counts = min(counts1, counts2)
print (counts)

这导致;

[~]$ python /tmp/test.py
letters: set(
['q', 'r']) intersection count: 2
letter1 q
letter1 r
letter1 t
letter2 q
letter2 s
letter2 r
counts1 3 counts2 3
3

分析,2是正确答案(q和r是两者共有的唯一字母),3是设置唯一值的较低数字。

答案 5 :(得分:0)

对每个字母进行计数,并采用最小值来找出这两个字母共有多少个字母。总结一下,这就是你的答案。

for letter in letters:
    counts1 += s1.count(letter)
    counts2 += s2.count(letter)
    counts += min(counts1, counts2)
    counts1 = 0
    counts2 = 0
print(counts)

答案 6 :(得分:0)

def commonCharacterCount(s1, s2):
    s=0
    for i in list(set(s1)):
        count1=0
        count2=0
        if i in s2:
            count1 = s1.count(i)
            count2=  s2.count(i)
            s=s+min(count1,count2)

    return(s)

答案 7 :(得分:0)

另一种方式,虽然很晚了...

def commonCharacterCount(s1, s2):
    
    count = 0
    
    for i in range(len(s1)):
        for j in range(len(s2)):
            if(s1[i]==s2[j]):
                count +=1
                s2 = s2.replace(s2[j],"",1)
                break
    return count