天天看點

Python實作兩個有序集合的交集和并集

    本文通過python實作簡易的集合交并算法,輸入是兩個以遞增順序排序的集合,輸出它們的有序交集和有序并集。

1、Union算法

def union(s1, s2):
    o = []
    i = j = 0
    s1_n = len(s1)
    s2_n = len(s2)
    while i < s1_n and j < s2_n:
        if s1[i] < s2[j]:
            o.append(s1[i])
            i += 1
        elif s1[i] == s2[j]:
            o.append(s1[i])
            i += 1
            j += 1
        else:
            o.append(s2[j])
            j += 1
    top = None
    if o: top = o[-1]
    if i < s1_n: o.extend(s1[i:] if s1[i] != top else s1[i+1:])
    if j < s2_n: o.extend(s2[j:] if s2[j] != top else s2[j+1:])
    return o
           

    算法圖解:

Python實作兩個有序集合的交集和并集

2、Intersect算法

def intersect(s1, s2):
     if len(s1) == 0 or len(s2) == 0:
         return None
     o = []
     i = j = 0
     m = min(s1[-1], s2[-1])
     while s1[i] < m and s2[j] < m:
         if s1[i] == s2[j]:
             o.append(s1[i])
             i += 1
             j += 1
         elif s1[i] < s2[j]:
             i += 1 
         else: 
             j += 1
     if (s1[-1] == s2[j] == m) or (s2[-1] == s1[i] == m):
         o.append(m)
     return o
           

    算法圖解 

Python實作兩個有序集合的交集和并集