List和Set里添加元素


在Python里往List和Set里添加元素有多种方法.

List

1
2
3
4
5
a = [1,2,3,4]
##用append
a.append(5)
##或者用+
a += [6]

Set

1
2
3
4
5
a = set([1,2,3,4])
##用add
a.add(5)
##用或运算符号
a |= {6}

Set还有个update函数,可以接受多组参数一次添加到set里

1
a.update([5,6,3], [-11,11])

一道Leetcode

Group Anagrams

https://leetcode.com/problems/anagrams/
Given an array of strings, group anagrams together.

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

[
[“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