【Python CheckiO 题解】Three Words
CheckiO 是面向初學(xué)者和高級(jí)程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰(zhàn)和有趣的任務(wù),從而提高你的編碼技能,本博客主要記錄自己用 Python 在闖關(guān)時(shí)的做題思路和實(shí)現(xiàn)代碼,同時(shí)也學(xué)習(xí)學(xué)習(xí)其他大神寫的代碼。
CheckiO 官網(wǎng):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
題目描述
【Three Words】:給定一個(gè)字符串,判斷其是否為連續(xù)的三個(gè)單詞(單詞非單個(gè)字母),單詞與數(shù)字之間會(huì)用空格隔開,例如:start 5 one two three 7 end,連續(xù)三個(gè)單詞為 one two three,返回為 True。
【鏈接】:https://py.checkio.org/mission/three-words/
【輸入】:字符串
【輸出】:True or False
【前提】:0 < len(words) < 100
【范例】:
checkio("Hello World hello") == True checkio("He is 123 man") == False checkio("1 2 3 4") == False checkio("bla bla bla bla") == True checkio("Hi") == False解題思路
直接利用 re 模塊的 findall() 方法,匹配三個(gè)連續(xù)的單詞,單詞之間以空格隔開,如果成功匹配,那么其長度應(yīng)該為 1,則返回 True,否則返回 False。
代碼實(shí)現(xiàn)
import redef checkio(words: str) -> bool:return len(re.findall('\D+\s\D+\s\D+', words)) == 1#These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__':print('Example:')print(checkio("Hello World hello"))assert checkio("Hello World hello") == True, "Hello"assert checkio("He is 123 man") == False, "123 man"assert checkio("1 2 3 4") == False, "Digits"assert checkio("bla bla bla bla") == True, "Bla Bla"assert checkio("Hi") == False, "Hi"print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")大神解答
大神解答 NO.1
def checkio(words):succ = 0for word in words.split():succ = (succ + 1)*word.isalpha()if succ == 3: return Trueelse: return False大神解答 NO.2
def checkio(words: str) -> bool:from re import findallreturn bool( findall(r"(\D+\s\D+\s\D+)",words))大神解答 NO.3
import recheckio = lambda words: re.search(r"(\b[a-zA-Z]+\b\s){2}\b[a-zA-Z]+\b", words) is not None大神解答 NO.4
import re def checkio(words):return bool(re.compile("([a-zA-Z]+ ){2}[a-zA-Z]+").search(words)) 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的【Python CheckiO 题解】Three Words的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从官方数据看,房价下跌城市只占少数,为什
- 下一篇: 【JS 逆向百例】网洛者反爬练习平台第一