CheckIO是一个通过闯关游戏学习编程的网站(Python和JavaScript)。通过解题开发新“岛屿”,同时,通过做任务获得Quest Points解锁会员题目。
文章内容:题目、我自己的思路和代码以及优秀代码,如果想看大神解题可以直接跳到“优秀代码”部分。
本题链接:https://py.checkio.org/en/mission/popular-words/
题目
在这项任务中,你要计算文本中每个要求的单词出现的次数。
给定两个参数:分别是文本和单词。
注意:
- 不区分大小写,如:“one”, “One”, “oNe”, "ONE"都算"one"的出现
- 要搜索的单词一般以小写形式给出
- 如果单词没有出现过,次数为0
- 文本中包含大写字母、小写字母和空格
输入: 文本和以列表形式给出的单词
输出: 以字典形式给出,其中各单词为字典的键,其出现的次数为对应的值
举个栗子:
popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
'i': 4,
'was': 3,
'three': 0,
'near': 0
}
难度: Elementary+
题目框架
def popular_words(text: str, words: list) -> dict:
# your code here
return None
if __name__ == '__main__':
print("Example:")
print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']))
# These "asserts" are used for self-checking and not for an auto-testing
assert popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
'i': 4,
'was': 3,
'three': 0,
'near': 0
}
print("Coding complete? Click 'Check' to earn cool rewards!")
思路
No.1
- 将
text
进行分割; - 创建字典,将
words
里的单词出现次数设为0
; - 遍历
text
,如果该单词在count
里,对应的次数+1
。
No.2
- 将
text
进行分割; - 创建
count
列表,添加words
里的单词在text
中出现次数; - 使用
zip()
函数,将words
和count
列表中的元素一一对应,形成元组,使用dict()
函数,将zip()
函数生成的元组转化为字典。
代码
No.1
def popular_words(text: str, words: list) -> dict:
# your code here
count = {}
text = text.lower().split()
for i in words:
count[i] = 0
for i in text:
if i in count:
count[i] += 1
return count
No.2 zip()
函数
def popular_words(text: str, words: list) -> dict:
# your code here
text = text.lower().split()
count = [text.count(i) for i in words]
return dict(zip(words, count))
优秀代码
No.1
def popular_words(text, words):
lower_count = text.lower().split().count
return {word: lower_count(word) for word in words}
原来可以这样,感觉像定义了一个函数,学到了
感觉和直接写到 return
里差不多?
No.2
def popular_words(text, words):
return dict(zip(words, map(text.lower().split().count, words)))
用了 map()
函数计算对应单词的出现次数
知识点
.split()
函数在不写参数时,默认为所有的空字符,包括空格、换行(\n
)、制表符(\t
)等