2017-07-17 86 views
4

我試圖匹配兩個字符串,直到第一個不匹配的字符,然後確定百分比完全匹配。我的代碼是這樣的:匹配兩個字符串(字符到字符),直到第一個不匹配使用python

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 

python中是否有任何內置的方法可以做得更快?爲了簡單起見,假設兩個字符串具有相同的長度。

+0

最接近的事情,這是'difflib'的['SequenceMatcher.get_matching_blocks'(https://docs.python.org/2/library/difflib.html#difflib.SequenceMatcher.get_matching_blocks): http://ideone.com/wlUVd9 –

+0

字符串可以作爲列表操作,不需要「列出()」它們。 – TemporalWolf

+0

最好的答案已經在評論中提供給https://stackoverflow.com/questions/18715688/find-common-substring-between-two-strings –

回答

6

有沒有內置在做整個事情,但你可以使用內置的用於計算共同的前綴:

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

極好的發現! –

4

我不認爲有這樣的內置方法。

但是你可以提高你的實現:

  • 沒有必要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 
0

替代

(剛纔看到我下面的答案想到同樣的事情,而我是編輯後)

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