我需要生成给定n个字符的Ki长度的所有可能单词,例如:
给予
LNDJOBEAWRL公司
做 熊
我想不出len 5这个词,但这就是我的想法
n = 11
k1 = 2
k2 = 4
k3 = 5
所以基本上所有的单词长度都是2,4和5,但是没有重复使用字符。最好的办法是什么?你知道吗
我的字典结构如下所示:
{
3: [{u'eit': u' "eit":0'}],
5: [{u'doosw': u' "woods": 4601, '}, {u'acenr': u' "caner": 0, '}, {u'acens': u' "canes": 0, '}, {u'acden': u' "caned": 0, '}, {u'aceln': u' "canel": 0,'}],
6: [{u'abeill': u' "alible": 0, '}, {u'cdeeit': u' "deciet":0,'}, {u'demoor': u' "mooder": 0, '}],
7: [{u'deiprss': u' "spiders": 0, '}, {u'deiprsy': u' "spidery": 0, '}, {u'cersttu': u' "scutter": 0, '}],
8: [{u'chiiilst': u' "chilitis": 0, '}, {u'agilnrtw': u' "trawling": 0, '}, {u'abdeemns': u' "beadsmen": 0, '}],
9: [{u'abeiilnns': u' "biennials": 0, '}, {u'bclooortu': u' "oblocutor": 0, '}, {u'aabfiinst': u' "fabianist": 0, '}, {u'acdeiituz': u' "diazeutic": 0, '}, {u'aabfiimns': u' "fabianism": 0, '}, {u'ehnoooppt': u' "optophone": 0, '}],
10: [{u'aiilnoprtt': u' "tripolitan": 0, '}, {u'eeilprrsty': u' "sperrylite": 0, '}, {u'gghhiilttt': u' "lighttight": 0, '}, {u'aeegilrruz': u' "regularize": 0, '}, {u'ellnprtuuy': u' "purulently": 0, '}],
11: [{u'cdgilnoostu': u' "outscolding": 0, '}],
12: [{u'ceeeilnostuy': u' "leucosyenite": 0, '}, {u'aacciloprsst': u' "sarcoplastic": 0, '}],
13: [{u'acdeimmoprrsu': u' "cardiospermum": 0, '}, {u'celnnooostuvy': u' "noncovetously": 0, '}],
14: [{u'adeejmnnoprrtu': u' "preadjournment": 0, '}]
}
我修改过的代码如下:
wlen = self.table[pos]
if pos == 0:
# See if the letters remaining in the bag are a valid word
key = ''.join(sorted(bag.elements()))
for d in wlen:
if key in d.keys():
yield solution + [key]
else:
pos -= 1
for dic in wlen:
print(len(dic))
for key in dic.keys():
下面的代码使用递归生成器构建解决方案。为了存储目标字母,我们使用^{} ,这就像一个允许重复项的集合。你知道吗
为了简化搜索,我们为所需的每个单词长度创建一个字典,将每个字典存储在一个名为
all_words
的字典中,单词长度作为关键字。每个子字典存储包含相同字母的单词列表,排序后的字母作为关键字,例如'aet': ['ate', 'eat', 'tea']
。你知道吗我使用标准的Unix'/usr/share/dict/words'word文件。如果使用不同格式的文件,可能需要修改将单词放入
all_words
的代码。你知道吗solve
函数从最小的字长开始搜索,一直搜索到最大的字长。如果包含最长单词的集合是最大的,那么这可能是最有效的顺序,因为最终的搜索是通过执行简单的dict查找来执行的,这非常快。以前的搜索必须测试该长度的子字典中的每个单词,寻找仍在目标包中的关键字。你知道吗输出
FWIW,以下是
输出
这段代码是为python3编写的。您可以在Python2.7上使用它,但需要进行更改
至
第一件事是标准化的话,这样两个字,互为字谜将处理完全相同。我们可以通过转换成小写并对单词的字母进行排序来实现这一点。下一步是区分给定字母的多次出现。为此,我们将每个字母映射到一个包含该字母的符号,以及一个表示该字母在字符串中出现的数字。你知道吗
现在我们已经有了每个单词的标准表示法,我们需要一种快速的方法来检查是否有任何排列与它们匹配。为此,我们使用trie datastructure。以下是一些入门代码:
现在需要将一个空的trie作为根,用任何东西作为符号,专门用来保存所有顶级尝试。然后迭代我们之前转换的每个单词,对于我们生成的第一个符号,检查根trie是否有一个子符号。如果没有,则为其创建一个trie并添加它。如果是,则转到下一个符号,并检查带有该符号的trie是否在上一个trie中。以这种方式继续,直到用尽所有符号,在这种情况下,当前trie节点表示我们转换的单词的标准化形式。将原单词存储在此trie中,然后继续下一个单词。你知道吗
完成后,整个单词列表将包含在这个trie数据结构中。然后,你可以这样做:
打印所有可以由目标单词的符号组成的单词。你知道吗
相关问题 更多 >
编程相关推荐