![](/img/trans.png)
[英]How can Python keep generating a random list of numbers until it equals to a certain made-up list?
[英]How to check if a string is only made-up from a list of words?
我有一个单词列表:
words = ['ABC', 'CDE', 'EFG']
如何检查我的字符串是否只包含该列表中的单词? 例如, 'EFG CDE'
结果为True
,因为'CDE'
和'EFG'
都在words
中。
我的代码如下:
lmn = []
for j in list(itertools.permutations(words, 2)) + list(itertools.permutations(words, 3)):
lmn.append(' '.join(j))
'EFG CDE' in lmn
我的输出是True
的。
但是对于像'EFG EFG CDE'
、 'CDE CDE CDE CDE'
这样的字符串,它不会给出True
,因为这些字符串不存在于lmn
中。 即使它们仅由列表['ABC', 'CDE', 'EFG']
组成。
这是我的做法:
allowed_words = set(['ABC','CDE','EFG'])
target_string = 'EFG EFG CDE'
print(all(word in allowed_words for word in target_string.split()))
与其尝试构建所有可能的排列然后检查(如果输入是无界的,这将是无界的),只需自己进行搜索。
问题是“检查字符串的每个组成部分是否存在于可迭代中”,其中组成部分定义为“由空格分隔的部分”:
def check_string_made_of_parts(candidate, parts):
return all(part in parts for part in candidate.split(" "))
对于 python 中的这些问题,在你编写任何代码之前用语言讨论一个合理的算法是很有帮助的。
如果你分解你的问题,你有一个允许单词的列表(可能是一组?)和一个由单词组成的字符串。
您想检查字符串中的每个单词是否都在允许的单词列表中。 松散地翻译,您要检查字符串中的单词集是否是允许的单词集的子集。
现在有两个步骤:
(1) 很简单 - words = set(s.split())
(2) 可以通过使用基本set
操作来完成:
words.issubset(allowed_words) # allowed_words doesn't need to be a set
words <= set(allowed_words)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.