我是靠谱客的博主 文艺蓝天,这篇文章主要介绍【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 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
}

解题思路

先将原字符串所有字母转换成小写字母,使用 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 dic


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
def popular_words(text, words):
    lower_count = text.lower().split().count
    return {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, 0
        while True:
            x = text.find(" "+i+" ", x+1)
            if x != -1:
                c += 1
            else:
                res.update({i: c})
                break
    return res

最后

以上就是文艺蓝天最近收集整理的关于【Python CheckiO 题解】Popular Words的全部内容,更多相关【Python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部