checkio练习题:three-words

Let's teach the Robots to distinguish words and numbers.

You are given a string with words and numbers separated by whitespaces (one space). 
The words contains only letters. You should check if the string contains three words in succession. 
For example, the string "start 5 one two three 7 end" contains three words in succession.

Input: A string with words.

Output: The answer as a boolean.

Example:

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

How it is used: This teaches you how to work with strings and introduces some useful functions.

Precondition: The input contains words and/or numbers. There are no mixed words (letters and digits combined).
0 < len(words) < 100


让我们教机器人区分单词和数字。
给你一个字符串,用空白(一个空格)分隔单词和数字。 单词只包含字母。 
您应该检查字符串是否包含三个字连续。 例如,字符串“start 5 one two three 7 end”连续包含三个单词。
输入:包含文字的字符串。
输出:作为布尔值的答案。

 

import re


def checkio(words: str) -> bool:
    # demo 1
    # c = 0
    # for i in words.split():  # 将用split方法分割的字符串for循环遍历
    #     if i.isalpha():  # 如果是字母的话则c自增1
    #         c += 1
    #     else:  # 关键点在这,如果其中有一次不是字母,都将c=0
    #         c = 0
    #     if c >= 3:  # 如果连续三次都是字母返回True
    #         return True
    # else:
    #     return False

    # demo 2
    # if re.search('\s?([a-zA-Z]+\s){2}[a-zA-Z]+\s?', words):
    #     return True
    # else:
    #     return False

    # demo 3
    # return bool(re.search(r'[a-zA-Z]+\s[a-zA-Z]+\s[a-zA-Z]+', words, flags=re.I))
    return bool(re.findall('\D+\s\D+\s\D+', words))


# These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    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"
    assert checkio("one two 3 four five six 7 eight 9 ten eleven 12") == True, "four five six"
    print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值