概述
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
题目描述
【Three Words】:给定一个字符串,判断其是否为连续的三个单词(单词非单个字母),单词与数字之间会用空格隔开,例如:start 5 one two three 7 end
,连续三个单词为 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()
方法,匹配三个连续的单词,单词之间以空格隔开,如果成功匹配,那么其长度应该为 1,则返回 True,否则返回 False。
代码实现
import re
def checkio(words: str) -> bool:
return len(re.findall('D+sD+sD+', 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 = 0
for word in words.split():
succ = (succ + 1)*word.isalpha()
if succ == 3: return True
else: return False
大神解答 NO.2
def checkio(words: str) -> bool:
from re import findall
return bool( findall(r"(D+sD+sD+)",words))
大神解答 NO.3
import re
checkio = lambda words: re.search(r"(b[a-zA-Z]+bs){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))
最后
以上就是懦弱自行车为你收集整理的【Python CheckiO 题解】Three Words的全部内容,希望文章能够帮你解决【Python CheckiO 题解】Three Words所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复