python - 要根据随机输入字母在字典中查找单词,这段代码会高效执行吗?
问题描述
我是编码新手。我试图构建一个简单的代码,它可以获取字母的子集并从基于文本的字典中返回一个有效的单词。
在下面的代码中,我要求用户输入一些字符(例如 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)
解决方案
列表对于查找来说效率低下。您应该使用集合的字典来索引每个单词和单词中的每个字母,这样您就可以简单地使用集合交集来查找包含所有给定字母的单词:
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'}}
这是上述代码的示例输入/输出,其中两个单词apple
和elephant
都包含两个字母a
and e
:
Please enter your letters: ae
{'apple', 'elephant'}
如果需要,您可以从这里轻松地根据给定的最小字母数过滤结果集。
推荐阅读
- reactjs - 映射函数在一个组件上渲染所有图像,而不是每个组件一个图像
- perl - 显式主包与隐式主包在哪些方面表现不同?
- java - 通过 SMTP 创建微软团队公告
- javascript - 按类型获取类 PropertyInfo
- snowflake-cloud-data-platform - Snowflake - 使目标表模式与源表变量列值保持同步
- signature - 亚马逊 sp-API aws 签名问题
- javascript - 当我尝试在 csv 中导出超过 1000 条记录时出现页面无响应错误?
- javascript - 在手风琴中搜索关键字突出显示
- c - 读写关闭的文件描述符
- php - 如何使用 Laravel Excel 将 Excel 导入数据库