Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

common letters in two strings

Tags:

python

string

I've been trying to solve this program which takes two strings as input and outputs number of common letters. For Example, if the input was "common" and "connor" then the output should be 4 ( 1 c , 1 n and 2 o's ).I used set() function but it outputs 3 ( it treats both o's as a single common letter ). Any help would be appreciated.Thanks!!!

Btw here's the code i wrote:

print("Enter number of inputs: ")
c = int(input())
store = []
for each_item in range(c):
    print("Enter First String: ")
    one = input()
    print("Enter Second String")
    two = input()
    s = len(set(one) & set(two))
    store.append(s)
for each_number in store:
    print(each_number)
like image 396
Pruthvi Raj Avatar asked Feb 15 '14 13:02

Pruthvi Raj


1 Answers

Use collections.Counter:

>>> from collections import Counter

>>> Counter('common')
Counter({'m': 2, 'o': 2, 'c': 1, 'n': 1})
>>> Counter('connor')
Counter({'o': 2, 'n': 2, 'c': 1, 'r': 1})

>>> common = Counter('common') & Counter('connor') # intersection
>>> common
Counter({'o': 2, 'c': 1, 'n': 1})
>>> sum(common.values())
4
like image 109
falsetru Avatar answered Sep 24 '22 17:09

falsetru