Pythonic way to merge two overlapping lists, preserving order

后端 未结 8 1596
鱼传尺愫
鱼传尺愫 2021-02-03 22:40

Alright, so I have two lists, as such:

  • They can and will have overlapping items, for example, [1, 2, 3, 4, 5], [4, 5, 6, 7].
  • The
8条回答
  •  一向
    一向 (楼主)
    2021-02-03 22:53

    I don't offer optimizations but another way of looking at the problem. To me, this seems like a particular case of http://en.wikipedia.org/wiki/Longest_common_substring_problem where the substring would always be at the end of the list/string. The following algorithm is the dynamic programming version.

    def longest_common_substring(s1, s2):
        m = [[0] * (1 + len(s2)) for i in xrange(1 + len(s1))]
        longest, x_longest = 0, 0
        for x in xrange(1, 1 + len(s1)):
            for y in xrange(1, 1 + len(s2)):
                if s1[x - 1] == s2[y - 1]:
                    m[x][y] = m[x - 1][y - 1] + 1
                    if m[x][y] > longest:
                        longest = m[x][y]
                        x_longest = x
                else:
                    m[x][y] = 0
        return x_longest - longest, x_longest
    
    master = [1,3,9,8,3,4,5]
    addition = [3,4,5,7,8]
    s, e = longest_common_substring(master, addition)
    if e - s > 1:
        print master[:s] + addition
    
    master = [9, 1, 1, 8, 7]
    addition = [8, 6, 7]
    s, e = longest_common_substring(master, addition)
    if e - s > 1:
        print master[:s] + addition
    else:
        print master + addition
    
    [1, 3, 9, 8, 3, 4, 5, 7, 8]
    [9, 1, 1, 8, 7, 8, 6, 7]
    

提交回复
热议问题