Python - how to find all intersections of two strings?

前端 未结 6 1691
花落未央
花落未央 2021-02-04 18:21

How to find all intersections (also called the longest common substrings) of two strings and their positions in both strings?

For example, if S1=\"never\"

6条回答
  •  误落风尘
    2021-02-04 19:02

    I'm assuming you only want substrings to match if they have the same absolute position within their respective strings. For example, "abcd", and "bcde" won't have any matches, even though both contain "bcd".

    a = "address"
    b = "oddness"
    
    #matches[x] is True if a[x] == b[x]
    matches = map(lambda x: x[0] == x[1], zip(list(a), list(b)))
    
    positions = filter(lambda x: matches[x], range(len(a)))
    substrings = filter(lambda x: x.find("_") == -1 and x != "","".join(map(lambda x: ["_", a[x]][matches[x]], range(len(a)))).split("_"))
    

    positions = [1, 2, 4, 5, 6]

    substrings = ['dd', 'ess']

    If you only want substrings, you can squish it into one line:

    filter(lambda x: x.find("_") == -1 and x != "","".join(map(lambda x: ["_", a[x]][map(lambda x: x[0] == x[1], zip(list(a), list(b)))[x]], range(len(a)))).split("_"))
    

提交回复
热议问题