clovis
clovis

Reputation: 335

Compare the characters in two strings regardless of their position

I have a function similarity(s, t) that compares two strings and the elements of said strings, regardless of their position, and returns the number of identical elements. The code I have:

def similarity(s, t):
   return sum(s == t for s, t in zip(s, t))

The only issue is that tests such as:

similarity('ab','ba') == 2

fail. I guess because it's only checking the first elements, and returning that result. Is there anyway to get around this whilst using zip() or should I take the more arduous route?

Upvotes: 1

Views: 1314

Answers (1)

MSeifert
MSeifert

Reputation: 152765

The easiest solution would be to use collections.Counter:

from collections import Counter

def similarity(a, b):
    cnts1 = Counter(a)
    cnts2 = Counter(b)
    diff = cnts1 - cnts2
    return len(a) - sum(diff.values())

    # or if you want it as one liner:
    # return len(a) - sum((Counter(a) - Counter(b)).values())

Which should work correct:

>>> similarity('ab', 'ba')
2
>>> similarity('aba', 'bab')
2

The problem with zip is that it zips the elements by index, so you only compare items at the same position.

Upvotes: 2

Related Questions