您的位置:首页 > 理论基础 > 数据结构算法

Python数据结构之集合Set

2017-07-02 11:01 639 查看
python中的Set()数据结构具有的一个特殊属性就是Set()中不存在重复元素

1、集合定义

a=set()


2、向Set中添加元素

a = set([1,2,3,4])
##用add
a.add(5)
##用或运算符号
a |= {6}
##Set还有个update函数,可以接受多组参数一次添加到set里
a.update([5,6,3], [-11,11])




3、Set中的元素排序

For any set 
s
 (or
anything else iterable), 
sorted(s)
 returns
a list of the elements of 
s
 in
sorted order:

b = sorted(a)  # sorted方法将返回一个list,而不是set



一道Leetcode

Group Anagrams

Given an array of strings, group anagrams together.

For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”],

Retur:

[

[“ate”, “eat”,”tea”],

[“nat”,”tan”],

[“bat”]

]

两个词如果是anagrams就把它们转为同一个值.

一般有两种转法,比如’tea’和’eat’排序后都可转为’aet’,或者统计字母出现的次数,两个都是((‘a’, 1), (‘e’, 1), (‘t’, 1)),然后再把这个转后的东西作为哈系表的键值key,对应的anagrams list作为value存进去。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
result = {}
for word in strs:
hash_key = ''.join(sorted(word))
if hash_key in result:
result[hash_key] += [word]
else:
result[hash_key] = [word]

return [tuple(sorted(lst)) for lst in result.values() ]

参考:http://sahandsaba.com/interview-question-facebook-anagrams.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: