【问题标题】:How to find the overlap between first n string that match last n string in others python 3?如何在其他python 3中找到与最后n个字符串匹配的第一个n个字符串之间的重叠?
【发布时间】:2020-03-13 16:34:36
【问题描述】:

假设我有两个字符串:

a = 'stackoverflow'
b =  'mathisgoodstackover'

我尝试从a 的开头找到与b 的结尾匹配的最大重叠部分。

c= 'stackover'
d = 'stackoverf'

c 是最优解。 d 不是,因为b 不以stackoverf 结尾。

我尝试使用蛮力,但不知道如何编写循环。有什么高效的算法吗?

谢谢,

【问题讨论】:

    标签: python-3.x string match prefix


    【解决方案1】:

    您可以将内置函数 max 与列表理解一起使用:

    max([a[:i] for i in range(1,len(a) + 1) if b.endswith(a[:i])], key=len)
    

    输出:

    'stackover'
    

    也适用于特殊情况:

    a = 'ssss'
    b =  'mathisgoodssssss'
    max([a[:i] for i in range(1,len(a) + 1) if a[:i] == b[-i:]], key=len)
    

    输出:

    'ssss'
    

    或者按照@ShadowRanger 的建议,您可以从i 开始尽可能大,然后使用next 内置函数和generator expression 缩小

    next((a[:i] for i in range(len(a), 0,-1) if b.endswith(a[:i])), '')
    

    【讨论】:

    • 使用b.endswith(a[:i]) 节省一点切片工作。您也可以向后工作,i 开始尽可能大并缩小,允许您使用带有genexpr 的next 而不是max+key=len(允许您在第一次命中时短路,因为所有其他命中必然会更小)。
    猜你喜欢
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    相关资源
    最近更新 更多