6

[Python] Intersection of Two Arrays

 2 years ago
source link: http://siongui.github.io/2018/03/17/python-match-common-element-in-two-array/
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] Intersection of Two Arrays

March 17, 2018

Find common elements in two arrays, i.e., intersection of two arrays in Python.

The idea is to convert one array 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 of the other array is in the hash table. If yes, the item is in the intersection of the two arrays.

The following is the implementation of above idea.

Run Code on repl.it

def intersection(a, b):
      map = {}

      for x in a:
              map[x] = True

      intersection = []
      for x in b:
              if x in map:
                      intersection.append(x)

      return intersection


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

The result will be [2 3 5].

The same idea can be used to find union of two arrays. See [1].

Tested on:


References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK