How to find list intersection?

前端 未结 12 2409
别那么骄傲
别那么骄傲 2020-11-22 05:21
a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c

actual output: [1,3,5,6] expected output: [1,3,5]

How can we ac

12条回答
  •  遇见更好的自我
    2020-11-22 05:44

    It might be late but I just thought I should share for the case where you are required to do it manually (show working - haha) OR when you need all elements to appear as many times as possible or when you also need it to be unique.

    Kindly note that tests have also been written for it.

    
    
        from nose.tools import assert_equal
    
        '''
        Given two lists, print out the list of overlapping elements
        '''
    
        def overlap(l_a, l_b):
            '''
            compare the two lists l_a and l_b and return the overlapping
            elements (intersecting) between the two
            '''
    
            #edge case is when they are the same lists
            if l_a == l_b:
                return [] #no overlapping elements
    
            output = []
    
            if len(l_a) == len(l_b):
                for i in range(l_a): #same length so either one applies
                    if l_a[i] in l_b:
                        output.append(l_a[i])
    
                #found all by now
                #return output #if repetition does not matter
                return list(set(output))
    
            else:
                #find the smallest and largest lists and go with that
                sm = l_a if len(l_a)  len(l_b) else l_b
    
                for i in range(len(sm)):
                    if sm[i] in lg:
                        output.append(sm[i])
    
                #return output #if repetition does not matter
                return list(set(output))
    
        ## Test the Above Implementation
    
        a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
        b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
        exp = [1, 2, 3, 5, 8, 13]
    
        c = [4, 4, 5, 6]
        d = [5, 7, 4, 8 ,6 ] #assuming it is not ordered
        exp2 = [4, 5, 6]
    
        class TestOverlap(object):
    
            def test(self, sol):
                t = sol(a, b)
                assert_equal(t, exp)
                print('Comparing the two lists produces')
                print(t)
    
                t = sol(c, d)
                assert_equal(t, exp2)
                print('Comparing the two lists produces')
                print(t)
    
                print('All Tests Passed!!')
    
        t = TestOverlap()
        t.test(overlap)
    
    

提交回复
热议问题