zoukankan      html  css  js  c++  java
  • Python活力练习Day21

    Day21:给定两个数组,编写一个函数来计算它们的交集。

      eg1 : input : nums1 = [1,2,2,1], nums2 = [2,2]

        output : [2,2]
      eg2 : input : nums1 = [4,9,5], nums2 = [9,4,9,8,4]

        output : [4,9]

    #如果要单纯的求出两个列表里面相同的元素,直接用set()即可

    #参考力扣大佬写的代码,实在是太妙了!!!

     方法一:

     1 def intersect(nums1, nums2):
     2     
     3     #求出两个列表共同的元素(唯一)
     4     #以【1,2,2,1】和【2,2】为例,inter = {2}
     5     inter = set(nums1) & set(nums2)  
     6     l = []
     7     for i in inter:
     8         #i的个数为2
     9         l += [i] * min(nums1.count(i), nums2.count(i))
    10 
    11     return l
    12 
    13 if __name__ == "__main__":
    14 
    15     nums1 = [1,2,2,1]
    16     nums2 = [2,2]
    17     print(intersect(nums1,nums2))
    18     

     方法二:双指针,先排序后进行遍历。

     1 def intersect(nums1, nums2):
     2     nums1.sort()
     3     nums2.sort()
     4     r = []
     5     left, right = 0, 0
     6     while left < len(nums1) and right < len(nums2):
     7         if nums1[left] < nums2[right]:
     8             left += 1
     9         elif nums1[left] == nums2[right]:
    10             r.append(nums1[left])
    11             left += 1
    12             right += 1
    13         else:
    14             right += 1
    15     return r

    输出结果:[2,2]

    #补充关于Python里面的交集,并集和差集运算

    #Python交集

    1 print([val for val in nums1 if val in nums2])
    2 print(list(set(nums1) & set(nums2)))
    3 print(list(set(nums1).intersection(set(nums2))))

    #Python并集

    1 print(list(set(nums1).union(set(nums2))))
    2 print(list(set(nums1) or set(nums2)))

    #Python差集

    1 print(list(set(nums1).difference(set(nums2))))
    2 #差集还可以是并集减去交集
    3 set_union = list(set(nums1).union(set(nums2)))
    4 set_inter = list(set(nums1).intersection(set(nums2)))
    5 set_diff = [i for i in set_union if i not in set_inter]
    6 print(set_diff)
  • 相关阅读:
    DataTable:数据库到程序的桥梁
    《Javascript高级程序设计》阅读记录(三):第五章 上
    《Javascript高级程序设计》阅读记录(二):第四章
    javascript获取窗口位置、绝对位置、事件位置等
    《Javascript高级程序设计》阅读记录(一):第二、三章
    调试用随笔
    C#值类型和引用类型
    vue使用vue-awesome-swiper及一些问题
    npm与yarn命令对比
    npm与nrm
  • 原文地址:https://www.cnblogs.com/xiaodangdang/p/12156574.html
Copyright © 2011-2022 走看看