5

[Python] Set Difference of Two Arrays

 2 years ago
source link: http://siongui.github.io/2018/03/21/python-set-difference-of-two-arrays/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Python] Set Difference of Two Arrays

March 21, 2018

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 x ∉ B}

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK