1189. “气球” 的最大数量
1.题目
给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 “balloon”(气球)。
字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 “balloon”。
示例 1:
输入:text = "nlaebolko"
输出:1
示例 2:
输入:text = "loonbalxballpoon"
输出:2
2.参考答案
代码如下(示例):
class Solution:
def maxNumberOfBalloons(self, text: str) -> int:
cnt = Counter([q for q in text if q in "balon"])
cnt['l'] //= 2
cnt['o'] //= 2
return min(cnt.values()) if len(cnt) == 5 else 0
3.知识点
①str.count()
str.count()方法用来统计字符串里某个字符出现的次数。
Str = "Tomorrow will be another day.The sun also rise"
print("len(Str):",len(Str))
输出结果:
len(Str):46
②list.count()
list.count()方法用来统计列表中某个元素出现的次数。
List = ['appel','pear','orange','banana','pear','mango','grape']
print("列表中'pear'出现的次数:",List.count('pear'))
输出结果:
列表中’pear’出现的次数: 2
③Counter() 函数
Counter()也可以用于统计字符出现的个数或列表中元素出现的次数。返回结果按出现次数从多至少排列。
一个Counter是一个dict的子类,用于计数可哈希对象。
Counter().most_common(n)返回数组中出现次数最多的元素。参数n表示的含义是:输出出现次数最多的前n个元素。
from collections import Counter
List = ['appel','pear','orange','banana','pear','mango','grape']
a = Counter(List)
print(a)
输出结果:
Counter({‘pear’: 2, ‘appel’: 1, ‘orange’: 1, ‘banana’: 1, ‘mango’: 1, ‘grape’: 1})
④整除//,取余%,
Python3中的除法中,除法/总是返回一个浮点数
>>> 6/4
1.5
如果只想得到整数的结果,丢弃分数部分,可以使用运算符 //
>>> 6//4
1
Python3 中采用%表示取模运算,结果返回除法的余数
>>> 21%10
1