根据随机输入的字母在字典中查找单词,此代码是否有效执行?

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


在下面的代码中,我要求用户输入一些字符(例如 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)


莫回无
浏览 261回答 3
3回答

慕沐林林

列表对于查找来说效率低下。你应该使用集合的字典来索引每个单词和单词中的每个字母,这样你就可以简单地使用集合交集来查找包含所有给定字母的单词:from functools import reduced = {}with open('C:\\english-dict2.txt') as f:&nbsp; &nbsp; for l in f:&nbsp; &nbsp; &nbsp; &nbsp; w = l.strip()&nbsp; &nbsp; &nbsp; &nbsp; for c in set(w):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 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]]))例如,给定以下单词的字典:applebookcatdogelephant索引字典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'}}这是上述代码的示例输入/输出,其中发现单词apple和elephant都包含字母a和e:Please enter your letters: ae{'apple', 'elephant'}如果需要,您可以从这里根据给定的最小字母数轻松过滤结果集。

ibeautiful

对于您的字典,您不需要遍历 using readline(),只需执行以下操作:with open(path) as fh:&nbsp; &nbsp; dict = readlines()即使出现错误,这也将安全地关闭您的文件。如果你想对单词进行查找,我会使用 aset而不是 a list,因为查找sets是 O(1),而查找list不是,它们是 O(n)。d_set = set(dict)这样,如果您想创建所有字母组合,您可以像这样查找它们:import itertoolsletters = input("Input your letters, please ")def check_for_match(combos):&nbsp; &nbsp; for combo in combos:&nbsp; &nbsp; &nbsp; &nbsp; if combo in d_set:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield comboi = len(letters)my_list = []while i:&nbsp; &nbsp; combos = itertools.permutations(words, i)&nbsp; &nbsp; results = list(check_for_match(combos))&nbsp; &nbsp; my_list = [*my_list, *results]&nbsp; &nbsp; i-=1这将为您提供 的所有排列letters,检查它们是否在您的字典中,并构建my_list它们。我想这就是你要找的

尚方宝剑之说

修改 1:您不需要遍历 中的字母letters,只需letters_list=list(letters)足以制作字母列表。修改2:您可以确保mini可以使用以下方法处理任何内容:try:&nbsp; &nbsp; mini = int(mini)except:&nbsp; &nbsp; mini = 2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python