2017-05-30 75 views
0

此代碼的輸出繼續爲4.但是,輸出應該爲3.設置的交集存在是因爲我相信這是答案的關鍵。答案爲4而不是3的原因來自s1中與s2相匹配的2 q和1 r的數量。計算字符串中的常見字符Python

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) 

任何幫助,非常感謝。

+1

你試圖實現什麼? –

+0

你能解釋爲什麼3是正確的答案嗎? – Mureinik

+0

在s1中有2個qs和1個r匹配s2。我只是想要輸出這個答案。 –

回答

3

如果你想保持普通的字符數的計數,你應該使用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

我換成你原來的代碼塊

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,你檢查設置(s1)包含rq 計數是正確的。同樣,如果檢查環的2,輸出爲:因此

q:3 
r:1 
s:1 

最小數爲4

0

做一個計數每個字母,並採取最低找出多少那字母對兩個字符串都是通用的。然後總結一下,這就是你的答案。

for letter in letters: 
    counts1 += s1.count(letter) 
    counts2 += s2.count(letter) 
    counts += min(counts1, counts2) 
    counts1 = 0 
    counts2 = 0 
print(counts) 
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) 
+0

您的回答是正確的。但是,我喜歡頂級答案的簡單性。 –

1

這裏是另一種不使用模塊來做到這一點。

sum(1 for i in zip(sorted(list(s1)), sorted(list(s2))) if len(set(i)) < 2) 

3 
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是任一組唯一值的較低數目。

+0

天哪我喜歡打印報表 –