Prakash
Prakash

Reputation: 11

Comparing Strings

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.

Upvotes: 0

Views: 9927

Answers (5)

Mahi S Nair
Mahi S Nair

Reputation: 1

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))

Upvotes: 0

Varnit Khandelwal
Varnit Khandelwal

Reputation: 121

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

import operator

operator.eq(String, String)

Upvotes: 1

gladysbixly
gladysbixly

Reputation: 2659

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())

Upvotes: 1

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

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.

Upvotes: 6

Senthil Kumaran
Senthil Kumaran

Reputation: 56813

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

Upvotes: 1

Related Questions