Untitled

 avatar
unknown
plain_text
10 months ago
855 B
16
Indexable
# 3) Union, intersection, difference (order-preserving as in sheet examples)
def my_union(list1, list2):
    result = []
    seen = set()
    for x in list1 + list2:
        if x not in seen:
            result.append(x)
            seen.add(x)
    return result

def my_intersection(list1, list2):
    set2 = set(list2)
    result = []
    seen = set()
    for x in list1:
        if x in set2 and x not in seen:
            result.append(x)
            seen.add(x)
    return result

def my_difference(list1, list2):
    set2 = set(list2)
    result = []
    for x in list1:
        if x not in set2 and x not in result:
            result.append(x)
    return result

# Example:
list1 = [3,1,2,7]
list2 = [4,1,2,5]
my_union(list1, list2)        # -> [3, 1, 2, 7, 4, 5]
my_intersection(list1, list2) # -> [1, 2]
my_difference(list1, list2)   # -> [3, 7]
Editor is loading...
Leave a Comment