Example intersection algorithm implemented two arrays Python3

This article introduces examples of paper-related operations Python3 implement the algorithm to calculate the intersection of two arrays, combined with two examples in the form of summary analysis of Python3 for traversing the array, bit operation and add elements, delete, etc. about the Python3 achieve two computing intersection algorithm array. Share to you for your reference, as follows:

problem:

Given two arrays, write a method to calculate their intersection.

Option One: Using collections.Counter the & operator, in one step, to find the minimum number of the same element. For skills, need friends can refer to the following

# -*- coding:utf-8 -*-
#! python3
def intersect(nums1, nums2):
  """
  :type nums1: List[int]
  :type nums2: List[int]
  :rtype: List[int]
  """
  import collections
  a, b = map(collections.Counter, (nums1, nums2))
  return list((a & b).elements())
#测试
arr1 = [1,2,3,4,5]
arr2 = [3,4,5,6,7]
print(intersect(arr1,arr2))

operation result:

[3, 4, 5]

Scheme II: wherein a traversed array, found that the addition to the list when new identical elements, while the deletion of one another identical element array

# -*- coding:utf-8 -*-
#! python3
def intersect(nums1, nums2):
  """
  :type nums1: List[int]
  :type nums2: List[int]
  :rtype: List[int]
  """
  res = []
  for k in nums1:
    if k in nums2:
      res.append(k)
      nums2.remove(k)
  return res
#测试
arr1 = [1,2,3,4,5]
arr2 = [3,4,5,6,7]
print(intersect(arr1,arr2))

operation result:

[3, 4, 5]

We recommend learning Python buckle qun: 913066266, look at how seniors are learning! From basic web development python script to, reptiles, django, data mining, etc. [PDF, actual source code], zero-based projects to combat data are finishing. Given to every little python partner! Every day, Daniel explain the timing Python technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering

Published 47 original articles · won praise 53 · views 50000 +

Guess you like

Origin blog.csdn.net/haoxun03/article/details/104270609