当前位置:首页 >> 编程语言 >> 【Python CheckiO 题解】Popular Words,firefox8

【Python CheckiO 题解】Popular Words,firefox8

0evadmin 编程语言 2
文件名:【Python CheckiO 题解】Popular Words,firefox8 【Python CheckiO 题解】Popular Words

CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。

CheckiO 官网:https://checkio.org/

我的 CheckiO 主页:https://py.checkio.org/user/TRHX/

CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise


题目描述

【Popular Words】:给定两个参数,第一个为字符串(text),第二个为字符串组成的列表(words),要求计算该列表各个元素在第一个字符串中出现的次数,不区分大小写,如果一次都没出现,则为 0,返回结果为一个字典。

【链接】:https://py.checkio.org/mission/popular-words/

【输入】:一个字符串和要搜索的词组成的列表

【输出】:字典,其中搜索词是键,值是这些词在给定文本中出现的次数

【前提】:输入文本将由大小写英文字母和空格组成

【范例】:

popular_words('''When I was OneI had just begunWhen I was TwoI was nearly new''', ['i', 'was', 'three', 'near']) == {'i': 4,'was': 3,'three': 0,'near': 0} 解题思路

先将原字符串所有字母转换成小写字母,使用 split() 方法对其进行分割,分割后的每个单词作为元素,组成一个新列表,然后利用 count() 方法计算 words 中每个单词在 text 中出现的次数,将搜索词作为键,将其出现的次数作为值,存入到字典当中即可。

代码实现 def popular_words(text: str, words: list) -> dict:text = text.lower().split()dic = {}for i in words:dic[i] = text.count(i)return dicif __name__ == '__main__':print("Example:")print(popular_words('''When I was OneI had just begunWhen I was TwoI was nearly new''', ['i', 'was', 'three', 'near']))# These "asserts" are used for self-checking and not for an auto-testingassert popular_words('''When I was OneI had just begunWhen I was TwoI 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 def popular_words(text, words):lower_count = text.lower().split().countreturn {word: lower_count(word) for word in words} 大神解答 NO.2 def popular_words(text, words):return dict(zip(words, map(text.lower().split().count, words))) 大神解答 NO.3 def popular_words(text: str, words):res = {}text = " "+text.lower().replace("\n", " ")+" "for i in words:x, c = -1, 0while True:x = text.find(" "+i+" ", x+1)if x != -1:c += 1else:res.update({i: c})breakreturn res
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接