首页 > 解决方案 > 要根据随机输入字母在字典中查找单词,这段代码会高效执行吗?

问题描述

我是编码新手。我试图构建一个简单的代码,它可以获取字母的子集并从基于文本的字典中返回一个有效的单词。

在下面的代码中,我要求用户输入一些字符(例如 abcdef),然后程序将用这些字母组成单词。

现在我的问题是,就性能、代码长度和块序列而言,这是最好的方法吗?如果没有,你能建议一个更好的方法吗?

#Read the dictionary

fh = open('C:\\english-dict2.txt')
dict = []
while True:
    line = fh.readline()
    dict.append(line.strip())
    if not line:
        break
fh.close()

#Input letters

letters = input("Please enter your letters: ")
letters_list=[]
for l in letters:
    letters_list.append(l)
mini = 2 #default value
maks = len(letters_list)
mini = input("Minimum length of the word (default is 2): ")

if mini == "":
    mini = 2 #default value
mini = int(mini)

#Here I create a new dictionary based on the number of letters input or less than.

newdic=[]

for words1 in dict:
    if len(words1) <= maks and len(words1)>= mini:
        newdic.append(words1)

for words2 in newdic:
    ok = 1

    for i in words2:
        if i in letters_list:
            ok = ok * 1
        else:
            ok = ok * 0

    if ok == 1:
        print(words2)

标签: pythonpython-3.x

解决方案


列表对于查找来说效率低下。您应该使用集合的字典来索引每个单词和单词中的每个字母,这样您就可以简单地使用集合交集来查找包含所有给定字母的单词:

from functools import reduce
d = {}
with open('C:\\english-dict2.txt') as f:
    for l in f:
        w = l.strip()
        for c in set(w):
            d.setdefault(c, set()).add(w)
letters = input("Please enter your letters: ")
print(reduce(lambda a, b: a & d[b], letters[1:], d[letters[0]]))

例如,给定以下单词的字典:

apple
book
cat
dog
elephant

索引字典d将变为:

{'p': {'elephant', 'apple'}, 'a': {'cat', 'elephant', 'apple'}, 'l': {'elephant', 'apple'}, 'e': {'elephant', 'apple'}, 'k': {'book'}, 'b': {'book'}, 'o': {'book', 'dog'}, 'c': {'cat'}, 't': {'cat', 'elephant'}, 'd': {'dog'}, 'g': {'dog'}, 'h': {'elephant'}, 'n': {'elephant'}}

这是上述代码的示例输入/输出,其中两个单词appleelephant都包含两个字母aand e

Please enter your letters: ae
{'apple', 'elephant'}

如果需要,您可以从这里轻松地根据给定的最小字母数过滤结果集。


推荐阅读