HOME: Three Words —— 判断连续元素的数据类型

这是一个关于在Python中检查字符串是否包含连续三个单词的编程挑战。题目要求字符串由空格分隔的单词和数字组成,且单词仅包含字母。解决方案包括分割字符串成列表,然后遍历列表判断连续三个元素是否全为单词,最后返回布尔结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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”包含三个连续的单词。

输入: 字符串
输出: 布尔值(TrueFalse

举个栗子:

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!")

思路及代码

思路

  1. 将字符串分割,形成列表
  2. 依次判断列表中连续3个元素是否为单词
  3. 如果都是单词,返回True
  4. 如果一直没有连续的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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值