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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With