[Python] Set Difference of Two Arrays


Find the elements in one array but not in the other, i.e., set difference of two arrays. In mathematical term:

A − B = {x ∈ A and xB}

The idea is to convert the array B to the data structure of key-value pairs, i.e., hash table. The hash table in Python is built-in dictionary type. Then we check if items in array A is in the hash table. If not, append the item to the difference array, and return the difference array after finish.

The following is the implementation of above idea.

Run Code on repl.it

# A - B
def difference(a, b):
      map = {}

      for x in b:
              map[x] = True

      diff = []
      for x in a:
              if x not in map:
                      diff.append(x)

      return diff

if __name__ == "__main__":
      a = [1, 2, 3, 4, 5]
      b = [2, 3, 5, 7, 11]
      print(difference(a, b))

The result will be [1, 4].

Tested on:


References:

[1][Python] Intersection of Two Arrays
[2][Python] Union of Two Arrays