Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match two strings (char to char) till the first non-match using python

I am trying to match two strings sequentially till the first the non-matched character and then determine the percentage exact match. My code is like this:

def match(a, b):
    a, b = list(a), list(b)
    count = 0
    for i in range(len(a)):
        if (a[i]!= b[i]): break
        else: count = count + 1
    return count/len(a)

a = '354575368987943'
b = '354535368987000'
c = '354575368987000'
print(match(a,b)) # return 0.267
print(match(a,c)) # return 0.8

Is there any built-in method in python already which can do it faster ? For simplicity assume that both strings are of same length.

like image 937
muazfaiz Avatar asked Dec 23 '22 16:12

muazfaiz


2 Answers

There's no built-in to do the entire thing, but you can use a built-in for computing the common prefix:

import os
def match(a, b):
    common = os.path.commonprefix([a, b])
    return float(len(common))/len(a)    
like image 117
bogdanciobanu Avatar answered May 01 '23 19:05

bogdanciobanu


I don't think there is such build-in method.

But you can improve your implementation:

  • No need to wrap the inputs in list(...). Strings are indexable.
  • No need for count variable, i already carries the same meaning. And you can return immediately when you know the result.

Like this, with some doctests added as a bonus:

def match(a, b):
    """
    >>> match('354575368987943', '354535368987000')
    0.26666666666666666

    >>> match('354575368987943', '354575368987000')
    0.8

    >>> match('354575368987943', '354575368987943')
    1
    """
    for i in range(len(a)):
        if a[i] != b[i]:
            return i / len(a)

    return 1
like image 23
janos Avatar answered May 01 '23 21:05

janos