【问题标题】:Match two strings (char to char) till the first non-match using python使用python匹配两个字符串(char到char)直到第一个不匹配
【发布时间】:2017-12-22 13:28:33
【问题描述】:

我试图按顺序匹配两个字符串,直到第一个不匹配的字符,然后确定百分比完全匹配。我的代码是这样的:

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 中是否已经有任何内置方法可以更快地完成它?为简单起见,假设两个字符串的长度相同。

【问题讨论】:

标签: python string-matching


【解决方案1】:

没有内置函数可以完成整个操作,但您可以使用内置函数来计算公共前缀:

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

【讨论】:

  • 很好的发现!
【解决方案2】:

我不认为有这样的内置方法。

但是你可以改进你的实现:

  • 无需将输入包装在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

【讨论】:

    【解决方案3】:

    替代

    (刚刚看到下面的回答我在编辑帖子的时候也想到了同样的事情)

    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
    

    【讨论】:

      猜你喜欢
      • 2021-09-18
      • 2011-10-09
      • 1970-01-01
      • 2019-12-01
      • 2014-08-05
      • 1970-01-01
      • 2022-01-17
      • 2021-04-11
      • 1970-01-01
      相关资源
      最近更新 更多