Python - how to find all intersections of two strings?

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

    Well, you're saying that you can't include any library. However, Python's standard difflib contains a function which does exactly what you expect. Considering that it is a Python interview question, familiarity with difflib might be what the interviewer expected.

    In [31]: import difflib
    
    In [32]: difflib.SequenceMatcher(None, "never", "forever").get_matching_blocks()
    Out[32]: [Match(a=1, b=3, size=4), Match(a=5, b=7, size=0)]
    
    
    In [33]: difflib.SequenceMatcher(None, "address", "oddness").get_matching_blocks()
    Out[33]: [Match(a=1, b=1, size=2), Match(a=4, b=4, size=3), Match(a=7, b=7, size=0)]
    

    You can always ignore the last Match tuple, since it's dummy (according to documentation).

提交回复
热议问题