题目:
You have a text and a list of words. You need to check if the words in a list appear in the same order as in the given text.
Cases you should expect while solving this challenge:
a word from the list is not in the text - your function should return False;
any word can appear more than once in a text - use only the first one;
two words in the given list are the same - your function should return False;
the condition is case sensitive, which means ‘hi’ and ‘Hi’ are two different words;
the text includes only English letters and spaces.
Input: Two arguments. The first one is a given text, the second is a list of words.
Output: A bool.
链接:
https://py.checkio.org/en/mission/words-order/
Example:
words_order(‘hi world im here’, [‘world’, ‘here’]) == True
words_order(‘hi world im here’, [‘here’, ‘world’]) == False
words_order(‘hi world im here’, [‘world’]) == True
words_order(‘hi world im here’,
[‘world’, ‘here’, ‘hi’]) == False
words_order(‘hi world im here’,
[‘world’, ‘im’, ‘here’]) == True
words_order(‘hi world im here’,
[‘world’, ‘hi’, ‘here’]) == False
words_order(‘hi world im here’, [‘world’, ‘world’]) == False
words_order(‘hi world im here’,
[‘country’, ‘world’]) == False
words_order(‘hi world im here’, [‘wo’, ‘rld’]) == False
words_order(’’, [‘world’, ‘here’]) == False
代码:
def words_order(text: str, words: list) -> bool:
import re
a = text
g = a.split(' ')
b = words
result = True
if len(b) <= 1:
if b[0] in g:
result = True
else:
result = False
if len(b) > 1:
for i in range(0, len(b)):
for j in range(i+1, len(b)) :
if b[i] in g and b[j] in g:
ix = g.index(b[i])
iy = g.index(b[j])
if ix >= iy:
result = False
break
else:
result = False
return result
```