生成所有可能的词 - 幼稚的方法。
基于Generate all permutations of all lengths:
import itertools..
symbols = ['Na','K','H']
for i in range(len(symbols)):
for word in itertools.permutations(symbols,i+1):
print( ''.join(word) )
您可以生成所有可能的组合,并根据字典检查它是否是实际单词。但它效率低下,并且仅适用于不允许重复符号的情况。
检查是否可以从符号构建单词 - 仍然不完美。
如果您允许重复,您需要根据符号列表检查一个单词。我提出以下建议:
import itertools..
words = ['K', 'NaH', 'NaNaNaNa', 'HaKuNa']
symbols = ['Na','K','H']
for i in range(len(symbols)):
for word in itertools.permutations(symbols,i+1):
print( ''.join(word) )
def can_be_built(word):
pos = 0
ret = True
while(pos < len(word)):
#following loop checks if word starting form `pos`
#can be prefixed by a symbol
symbol_match = False
for symbol in symbols:
if word[pos:pos+len(symbol)] == symbol:
symbol_match = True
break
if symbol_match == False:
print('Word `{}` has no match for symbol from: {}'.format(word, word[pos:]))
ret = False
break
#if it does move forward
pos += len(symbol)
return ret
for word in words:
print("{} can be built? {}".format(word, can_be_built(word)))
它迭代地检查一个单词前缀是否是一个符号,然后向前移动直到到达单词的结尾。
输出:
K can be built? True
NaH can be built? True
NaNaNaNa can be built? True
Word `HaKuNa` has no match for symbol from: aKuNa
HaKuNa can be built? False
它仍然不完美。
正确的方法
正如 Makoto 所说,前缀检查应该返回每个可能匹配项的列表。该算法应该从这些匹配中创建一个队列,并检查所有可能的路径。这有点像构建一个匹配单词的前缀图。如果一个人构建了整个单词,你就回家了。
我认为更正我的第二个示例仍然相当容易,但我没有时间编写实际代码。我认为这是一个很好的起点。