CheckIO是一个通过闯关游戏学习编程的网站(Python和JavaScript)。通过解题开发新“岛屿”,同时,通过做任务获得Quest Points解锁会员题目。
文章内容:题目、我自己的思路和代码以及优秀代码,如果想看大神解题可以直接跳到“优秀代码”部分。
本题链接:https://py.checkio.org/en/mission/three-words/
题目
给定一个字符串,该字符串由空格(一个空格)分隔单词和数字,这些单词部分只包含字母。检查字符串是否连续包含三个单词。例如,字符串“Start 5 1 2 3 7 End”连续包含三个单词。您将得到一个字符串,该字符串由空格(一个空格)分隔单词和数字。这些单词只包含字母。您应该检查字符串是否连续包含三个单词。例如,字符串“start 5 one two three 7 end”包含三个连续的单词。
输入: 字符串
输出: 布尔值(True
或False
)
举个栗子:
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
应用场景:对字符串的操作
假设:
- 字符串包含单词和/或数字,没有字母和数字混合在一起的词
- 0 <字符串长度 < 100
难度: Elementary
题目框架
def checkio(words) :
# Your code here
return False
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!")
思路及代码
思路
- 将字符串分割,形成列表
- 依次判断列表中连续3个元素是否为单词
- 如果都是单词,返回
True
- 如果一直没有连续的3个单词,返回
False
代码
def checkio(words: str) -> bool:
l1 = words.split()
for i in range(len(l1)-2):
if l1[i].isalpha() and l1[i+1].isalpha() and l1[i+2].isalpha():
return True
return False
优秀代码
No.1
def checkio(words):
succ = 0
for word in words.split():
succ = (succ + 1)*word.isalpha()
if succ == 3:
return True
return False
No.2
import re
def checkio(words):
return bool(re.compile("([a-zA-Z]+ ){2}[a-zA-Z]+").search(words))
或:
import re
def checkio(words):
return bool(re.search('\D+ \D+ \D+', words))
No.3
def checkio(words):
words = words.split()
for num in range(len(words) - 2):
if all(elem.isalpha() for elem in words[num: num + 3]):
return True
return False