【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 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總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Popular Words的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浦发随借金提前还款手续费多少_浦发随借金
- 下一篇: Flume-ng运行出错: Cause