Python3实现计算两个数组的交集算法示例

yipeiwu_com5年前Python基础

本文实例讲述了Python3实现计算两个数组的交集算法。分享给大家供大家参考,具体如下:

问题:

给定两个数组,写一个方法来计算它们的交集。

方案一:利用collections.Counter&运算,一步到位,找到 最小次数 的相同元素。

# -*- 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))

运行结果:

[3, 4, 5]

方案二:遍历其中一个数组,发现相同元素时添加到新列表中,同时删去另一个数组中的一个相同元素

# -*- 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))

运行结果:

[3, 4, 5]

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python Django Cookie 简单用法解析

Python Django Cookie 简单用法解析

home.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT...

Python中with及contextlib的用法详解

Python中with及contextlib的用法详解

本文实例讲述了Python中with及contextlib的用法。分享给大家供大家参考,具体如下: 平常Coding过程中,经常使用到的with场景是(打开文件进行文件处理,然后隐式地执...

python数据结构之链表的实例讲解

python数据结构之链表的实例讲解

在程序中,经常需要将⼀组(通常是同为某个类型的)数据元素作为整体 管理和使⽤,需要创建这种元素组,⽤变量记录它们,传进传出函数等。 ҳ...

详解python while 函数及while和for的区别

详解python while 函数及while和for的区别

1.while循环(只有在条件表达式成立的时候才会进入while循环) while 条件表达式:   pass while 条件表达式:   pass else:   pass 不知道...

Python打印“菱形”星号代码方法

Python打印“菱形”星号代码方法

本人是一名python初学者,刚刚看到一道有趣的python问题,“用python如何在编译器中打印出菱形图案?” 因此决定尝试一下,代码不多,仅供参考。 代码 def print...