python set的应用

You are given two sorted arrays that contain only integers. Your task is to find a way to merge them into a single one, sorted inascending order. Complete the function mergeArrays(arr1, arr2), where arr1 and arr2 are the original sorted arrays.

You don't need to worry about validation, since arr1 and arr2must be arrays with 0 or more Integers. If both arr1 and arr2 are empty, then just return an empty array.

Note: arr1 and arr2 may be sorted in different orders. Alsoarr1 and arr2 may have same integers. Remove duplicated in the returned result.

Examples

arr1 = [1, 2, 3, 4, 5];
arr2 = [6, 7, 8, 9, 10];
mergeArrays(arr1, arr2);  // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr3 = [1, 3, 5, 7, 9];
arr4 = [10, 8, 6, 4, 2];
mergeArrays(arr3, arr4);  // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

arr5 = [1, 3, 5, 7, 9, 11, 12];
arr6 = [1, 2, 3, 4, 5, 10, 12];
mergeArrays(arr5, arr6);  // [1, 2, 3, 4, 5, 7, 9, 10, 11, 12]

 

 这个问题可以用list.extend()连接两个list,然后去重,最后list.sort();不过python本身有内建函数set()。在python中,set是基本的数据类型,包含可变集合set(),和不可变集合frozenset()两种。set()集合是无序(所以不能用切片)且不重复的。

创建一个集合

>>> set('boy')
set(['y', 'b', 'o'])
>>> set('boyboyboy')
set(['y', 'b', 'o'])

添加元素,add-整体添加,update-拆分添加,效果上有区别

>>> s=set('girl')
>>> s
set(['i', 'r', 'l', 'g'])
>>> s.add('boy')
>>> s
set(['i', 'boy', 'r', 'l', 'g'])
>>> s.update('man')
>>> s
set(['a', 'boy', 'g', 'i', 'm', 'l', 'n', 'r'])

删除元素

>>> s=set('boy')
>>> s
set(['y', 'b', 'o'])
>>> s.remove('o')
>>> s
set(['y', 'b'])

集合的操作符号

数学符号python操作符含义
--

差集,相对补集

&交集
|并集
in是成员关系
not in不是成员关系
等于==等于
不等于!=不等于

所以按照集合的思想,本文开头的问题可以这样解决

def func(arr1,arr2):
    return sorted(set(arr1)|set(arr2))

或者直接按照集合的互异性,set()函数本身返回的便是一个集合,因此本身就有去重的功能,可以

def func(arr1,arr2):
    return sorted(set(arr1+arr2))

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值