How to Subtract Arrays in Python

The challenge

Implement a difference function, which subtracts one list from another and returns the result.

It should remove all values from list a, which are present in list b keeping their order.

arrayDiff([1,2],[1]) == [2]
Code language: Python (python)

If a value is present in b, all of its occurrences must be removed from the other:

arrayDiff([1,2,2,2,3],[2]) == [1,3]
Code language: Python (python)

The solution in Python

Option 1:

def array_diff(a, b): return [x for x in a if x not in b]
Code language: Python (python)

Option 2:

def array_diff(a, b): return filter(lambda i: i not in b, a)
Code language: Python (python)

Option 3:

def array_diff(a, b): for i in range(len(b)): while b[i] in a: a.remove(b[i]) return a
Code language: Python (python)

Test cases to validate our solution

import test from solution import array_diff @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(array_diff([1,2], [1]), [2], "a was [1,2], b was [1], expected [2]") test.assert_equals(array_diff([1,2,2], [1]), [2,2], "a was [1,2,2], b was [1], expected [2,2]") test.assert_equals(array_diff([1,2,2], [2]), [1], "a was [1,2,2], b was [2], expected [1]") test.assert_equals(array_diff([1,2,2], []), [1,2,2], "a was [1,2,2], b was [], expected [1,2,2]") test.assert_equals(array_diff([], [1,2]), [], "a was [], b was [1,2], expected []") test.assert_equals(array_diff([1,2,3], [1, 2]), [3], "a was [1,2,3], b was [1, 2], expected [3]")
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments