5

[Python] Union of Two Arrays

 2 years ago
source link: http://siongui.github.io/2018/03/20/python-set-of-all-elements-in-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] Union of Two Arrays

March 20, 2018

Find the set of all elements in two arrays, i.e., union 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 not, append the item to the first array, and return the first array after finish.

The following is the implementation of above idea.

Run Code on repl.it

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

      for x in a:
              map[x] = True

      for x in b:
              if x not in map:
                      a.append(x)

      return a


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

The result will be [1, 2, 3, 4, 5, 7, 11].

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

Tested on:


References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK