这个题很有意思,第一眼看上去我的反应是用哈希表做,建立一个字母和频次的对应关系。具体来说是建立j个不同的字典,[key:字母]->[value:频次],最后合并(或者每次更新一个总的字典),每个字母对应的频次求max值, 最后求和。
class Solution(object):
def minNumBooths(self, demand):
"""
:type demand: List[str]
:rtype: int
"""
dict_all = {}
for i in demand:
for key, value in Counter(i).items():
dict_all[key] = max(dict_all.get(key,0), value)
return sum(dict_all.values())
看了题解发现一种很聪明的方法,用reduce()函数+Counter迭代器做。如下,可以更简洁地实现。
class Solution(object):
def minNumBooths(self, demand):
"""
:type demand: List[str]
:rtype: int
"""
return sum(reduce(or_, map(Counter, demand)).values())
涉及的知识点:
Counter()是 collections 库中的一个函数,可以用来统计一个 python 列表、字符串、元组等 可迭代对象中每个元素出现的次数,并返回一个 字典。
Counter函数的功能主要是计数器,特别是在对源数据是字典类型的数据进行计数时,如果不想写冗长繁琐的for循环,那么使用Counter函数将是一个不错的选择。
https://blog.csdn.net/Flag_ing/article/details/124026747
from collections import Counter
nums = [1,2,3,4,5]
count = Counter(nums)
for k,v in count.items():
print(k,v)
map()函数
map() 会根据提供的函数对指定序列做映射。
第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的 新列表。
https://www.runoob.com/python/python-func-map.html
map(function, iterable, ...)
>>> def square(x) : # 计算平方数
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
<map object at 0x100d3d550> # 返回迭代器
>>> list(map(square, [1,2,3,4,5])) # 使用 list() 转换为列表
[1, 4, 9, 16, 25]
>>> list(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
reduce() 函数会对参数序列中元素进行累积。
函数将一个数据集合(链表,元组等)中的所有数据进行下列操作:用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算, 最后得到一个结果。
https://www.runoob.com/python/python-func-reduce.html
reduce(function, iterable[, initializer])
# function -- 函数,有两个参数
# iterable -- 可迭代对象
# initializer -- 可选,初始参数
from functools import reduce
def add(x, y) : # 两数相加
return x + y
sum1 = reduce(add, [1,2,3,4,5]) # 计算列表和:1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5]) # 使用 lambda 匿名函数
print(sum1)
print(sum2)
# 15
# 15
or_
在python中,我们可以将列表汇总为:sum(list_of_integers)。
现在,sum只是使用运算符+在两个元素之间进行的运算。
想用不同的运算符(例如or,and,xor等)对列表求和怎么办?
functools.reduce非常适合此用例。 它需要一个函数应用于累加值和下一个值,要减少的可迭代项以及可选的初始化程序。
可以使用operator模块,operator模块(位于标准库中,因此应始终可用)也将所有其他标准操作定义为函数,但对于or和and,将添加尾随_,因为它们是保留关键字:
from operator import or_, and_
reduce(or_, [1, 2, 3])
reduce(and_, [1, 2, 3])
尽管对于这两个,可以使用内置函数any和all:
from operator import or_
也可以用lambda表达式代替:
return sum(reduce(lambda a,b: a|b, map(Counter, demand)).values())