【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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WuKongSecurity@BOB

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值