Python - how to find all intersections of two strings?

前端 未结 6 1702
花落未央
花落未央 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:07

    Here's what I could come up with:

    import itertools
    
    def longest_common_substring(s1, s2):
       set1 = set(s1[begin:end] for (begin, end) in
                  itertools.combinations(range(len(s1)+1), 2))
       set2 = set(s2[begin:end] for (begin, end) in
                  itertools.combinations(range(len(s2)+1), 2))
       common = set1.intersection(set2)
       maximal = [com for com in common
                  if sum((s.find(com) for s in common)) == -1 * (len(common)-1)]
       return [(s, s1.index(s), s2.index(s)) for s in maximal]
    

    Checking some values:

    >>> longest_common_substring('address', 'oddness')
    [('dd', 1, 1), ('ess', 4, 4)]
    >>> longest_common_substring('never', 'forever')
    [('ever', 1, 3)]
    >>> longest_common_substring('call', 'wall')
    [('all', 1, 1)]
    >>> longest_common_substring('abcd1234', '1234abcd')
    [('abcd', 0, 4), ('1234', 4, 0)]
    

提交回复
热议问题