任务:如果字符串中有三个连续的单词,则打印 True,否则打印 False。该行包含数字和单词。如果单词之间有数字,我的代码将无法正常工作。添加条件result != []
并没有解决问题,我没有想法。
import re
def checkio(words: str) -> bool:
str_ = words.split()
sum_ = 0
for i in str_:
result = re.findall(r'[\w*\']+', i)
if len(result)!=0 and result != []:
sum_ = sum_+ 1
if sum_ >= 3:
return True
else:
return False
#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!")
在此先感谢您的帮助。
逻辑:
一定要定期吗?您也可以这样做,例如:
正则表达式解决方案:
测试:
使用正则表达式(选择三个可以包含数字但不能是数字的连续单词):
更新:
re.match()
->re.findall()