Align two lines (char to char) until the first inconsistency using python

I try to consistently match two lines to the first inconsistent character, and then determine the exact match in percent. My code is as follows:

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 a python built-in method that can do this faster? For simplicity, suppose both lines are the same length.

+4
source share
3 answers

There is no built-in application, but you can use the built-in to calculate the common prefix:

import os
def match(a, b):
    common = os.path.commonprefix([a, b])
    return float(len(common))/len(a)    
+6
source

I do not think there is such a built-in method.

But you can improve your implementation:

  • list(...). .
  • count, i . , .

, , :

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
+4

alternative

(Just now I saw that the answer below me was thinking the same thing when I edited the message)

def match(l1, l2):
    # find mismatch
    try:
        stop = next(i for i, (el1, el2) in enumerate(zip(l1, l2)) if el1 != el2)
        return stop/len(l1)
    except StopIteration:
        return 1
0
source

Source: https://habr.com/ru/post/1681646/


All Articles