Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of common letters in two strings

I have this code using collections Counter to find the number of common letters in two strings.

from collections import Counter

a = "abcc"
b = "bcaa"

answer = 0

ac = Counter(a)
bc = Counter(b)

for key in ac:
    answer += min(ac[key], bc[key])

print answer

The solution tries to find the number of common letters in both strings(Same letters still counted) My question is, I developped this logic but I fear it may be a wheel reinvented. Are there any introduced methods, or an easier way of doing this ?

Note: My question is different than the questions that tries to find the common letters between strings, I just need the count so I expect to find something basic.

like image 514
Max Paython Avatar asked May 04 '16 11:05

Max Paython


Video Answer


1 Answers

No, as far as I know, you did not reinvent the wheel. Your solution is very concise already. You could shorten the code a bit using the sum function and then put it into a dedicated function to emphasize the simplicity:

def num_common_letters(a, b):
    ac = Counter(a)
    bc = Counter(b)
    return sum(min(ac[key], bc[key]) for key in ac)

There's not much to strip away here.

like image 165
Frerich Raabe Avatar answered Oct 19 '22 19:10

Frerich Raabe