- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的问题是是否可以改进这些代码,使我的代码中的文字定义的单词列表可以更快地搜索整个 word_list.txt 文件。有人告诉我,有一种方法可以通过将所有 14 个单词放在适当的数据结构中来遍历文件一次。
word_list = ['serve','rival','lovely','caveat','devote',\
'irving','livery','selves','latvian','saviour',\
'observe','octavian','dovetail','Levantine']
def sorted_word(word):
"""This return the sorted word"""
list_chars = list(word)
list_chars.sort()
word_sort = ''.join(list_chars)
return word_sort
print("Please wait for a few moment...")
print()
#Create a empty dictionary to store our word and the anagrams
dictionary = {}
for words in word_list:
value = [] #Create an empty list for values for the key
individual_word_string = words.lower()
for word in open ('word_list.txt'):
word1 = word.strip().lower() #Use for comparing
#When sorted words are the same, update the dictionary
if sorted_word(individual_word_string) == sorted_word(word1):
if word1[0] == 'v':
value.append(word.strip()) #Print original word in word_list
tempDict = {individual_word_string:value}
dictionary.update(tempDict)
#Print dictionary
for key,value in dictionary.items():
print("{:<10} = {:<}".format(key,value))
由于新用户限制,我无法发布我的结果图片。顺便说一句,结果应该打印出每个单词以 v 开头的字谜。很高兴为改进此代码提供任何帮助。
最佳答案
如果您有足够的内存,您可以尝试将值存储到字典中,然后对其执行散列搜索(非常快)。这样做的好处是你可以 pickle 它以备将来再次使用(创建字典的过程很慢,查找很快)。如果你有非常大的数据集,你可能想使用 map reduce,disco-project 是我推荐的一个很好的 python/erlang 框架。
word_list = ['serve','rival','lovely','caveat','devote',\
'irving','livery','selves','latvian','saviour',\
'observe','octavian','dovetail','Levantine']
print("Please wait for a few moment...")
print()
anagrams = {}
for word in open ('word_list.txt'):
word = word.strip().lower() #Use for comparing
key = tuple(sorted(word))
anagrams[key] = anagrams.get(key,[]) + [word]
for word in word_list:
print "%s -> %s" % (word.lower(),aragrams[tuple(sorted(word.lower()))])
关于python - 改进字谜搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12970910/
我的程序运行良好,这只是我需要的一个小建议;首先这是我的代码,用于检查两个单词是否是字谜;效果很好; #include int anagram_check(char [], char []); in
面试问题给定两个输入字符串,您只能交换字符串中的两个连续元素。您必须展示将一个字符串转换为另一个字符串的所有步骤(两个字符串将是彼此的字谜)。例如。口香糖到马克杯 古姆百货公司通用汽车大学微量气体发生
我正在尝试学习 Python。考虑这个简单的 C 语言变位词检查器: bool are_anagrams(const char* str1, const char* str2) { int str
(下面关于我的问题的代码) 根据 this stack overflow question我使用 Pegolon 的方法来生成 NSString 中一组字符的所有可能排列。但是,我现在试图让它不仅生成
testing if strings are anagrams有很多种方式.但是,我想知道是否有一种方法可以只对每个单词进行一次迭代?如果不是,在 Python 中最有效的方法是什么? 我们可以遍历第
我是一名优秀的程序员,十分优秀!