0

Does there exist any inbuilt function in python than can return number of mathching characters in two strings,for example:

INPUT:

   TICK TOCK
   CAT DOG
   APPLE APPLES

OUTPUT:

 3
 0
 5

The words "TICK" and "TOCK" have a score of 3, since three characters (T, C, K) are the same. Similarly, "CAT" and "DOG" score 0, since no letters match.

I am a new bie in python so please help me with examples.

3
  • Cant think of anything other than re, for regular expression searching. Commented Mar 11, 2011 at 0:26
  • 1
    What do you want returned for "CAT TAC"? That is, does the order of characters in the string matter? What about "CAT CHAT"? Commented Mar 11, 2011 at 0:44
  • What about ABCDEF and BCDEF? 5 or 0? Commented Mar 11, 2011 at 1:44

5 Answers 5

6

Here's a version using list comprehensions:

[x == y for (x, y) in zip("TICK", "TOCK")].count(True)

Or, shorter (using operator):

import operator
map(operator.eq, "TICK", "TOCK").count(True)

According to @Kabie, <expr>.count(True) can be replaced by sum(<expr>) in both versions.

Sign up to request clarification or add additional context in comments.

4 Comments

Could you please explain this solutions?
The first one creates a list of tuples, each of which contains corresponding characters from the two strings (in the example, [('T', 'T'), ('I', 'O'), ('C', 'C'), ('K', 'K')]). The comprehension then changes each tuple into either True or False based on whether the characters are equal, and then count(True) determines the number of matches. The second one is similar; map applies its first argument (operator.eq) to corresponding elements of the other arguments. The operator.eq function is the same as the == operator, except that it can be passed to functions like map.
Just sum(map(operator.eq, "APPLE","APPLES"))
@JeremiahWillcock I think you better add that to your answer.
1

There is no built-in function. But you can do it using some simple expressions,.

>>> A, B = sorted("APPLE APPLES".split(), key=len)
>>> len([e for e in A if e in B])
5

1 Comment

Corrected the answer. Sorry guys, overlooked the repetitive part.
1

If the position and order of the characters are important, then the chosen answer would suffice. The problem is, the given solution will not work if that is not the case.

If position is not important, but the order is, you could write a function that returns the length of the longest common subsequence. Here is a sample implementation:

def lcs(string1, string2):
    m = len(string1)
    n = len(string2)

    C = [[0] * (n + 1)] * (m + 1)
    for i in range(m + 1)[1:]:
        for j in range(n + 1)[1:]:
            if string1[i - 1] == string2[j - 1]:
                C[i][j] = C[i - 1][j - 1] + 1
            else:
                C[i][j] = max(C[i][j - 1], C[i - 1][j])
    return C[m][n]

If position and order does not matter, you can use collections.Counter (Python 2.7/3.1; or http://code.activestate.com/recipes/576611/) like so:

def f(string1, string2):
    set_string1 = Counter(string1)
    set_string2 = Counter(string2)

    # get common characters
    common = set_string1 & set_string2

    # return the sum of the number of occurrences for each character
    return reduce(lambda a, b: a + b, common.values())

Comments

1

Yes you import operator by writing import operator and use operator.eq method like this:

import operator

operator.eq(String, String)

Comments

0

Hope this will help:

def CommonLetters(s1, s2):
    
    l1 = list(''.join(s1.split()))
    l2 = list(''.join(s2.split()))

    return [x for x in l1 if x in l2]

x = CommonLetters('cerberus', 'atorb')
print(len(x))

1 Comment

You could improve the general utility of your answer by providing some more clarification on what the posted code does.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.