<p>首先,我们根据每个字符串的长度对列表进行排序,以便pend_words函数可以找到它正在检查的单词中最大的单词</p> <p>例如:字符串“catscats”同时包含“cat”和“cats”,但如果它选择“cat”作为“catscats”的一部分,我们的程序将永远无法找到“cats”。如果“cat”不在我们的字符串中,程序将在遍历已排序字符串列表时逐渐找到“cat”</p>
<p>函数<code>pend_words</code>检索列表中包含其他单词的单词,并删除该部分单词</p>
<p>函数<code>confirm_words</code>检查挂起列表。对于列表中的每个空字符串,这意味着该字符串完全由其他单词组成,因此它会将该单词添加到<code>justified</code>列表中</p>
<pre><code>l = ['cats','cat','dogcats','dog','catpig','pigs','pigspigs','goatdog','goat','rabbit']
def pend_words():
global word,modified
for _ in range(len(word)):
for wor in l:
if wor in word and not(wor == word and modified==False):
word = word.replace(wor,'',1)
modified = True
pending.append(wor)
def confirm_words():
global word
if word == '':
for wo in pending:
if wo not in justfied:
justfied.append(wo)
l.sort(key=len,reverse=True)
justfied = []
for word in l:
pending = [] # Create an empty list to pend each potential word (potential because it contains another word)
modified = False # Before we pend the word, the word hasn't been modified
pend_words()
confirm_words()
print(justfied)
</code></pre>