我试图找到一个简单的方法来解决一个anagram和显示这些anagram的英文单词在返回页。目前,这显示在解算器页面上的排列,有些工作,但我想显示那些只是实际的话
任何建议都非常感谢
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('main.html')
else:
myLetters = request.form['letters']
myLetters = ''.join(sorted(myLetters))
myLetters = myLetters.strip()
myWords = []
myLetterList = list(myLetters)
lettersLength = len(myLetterList)
myWords = [''.join(result) for result in permutations(myLetters)]
with open("/usr/share/dict/words") as defaultWords:
for word in myWords:
if word not in defaultWords:
myWords.remove(word)
return render_template('solver.html', myLetters = myLetters, myWords = myWords)
问题是:
对文件使用
in
运算符会产生意外的结果文件不支持
__contains__
,但它们的行为类似于行序列,因此if word in file
只是在行上迭代,并产生意外的效果:相反,在文件中创建一组所有单词(使用
strip
清除多余的空白):并使用
words
进行查找编辑:一旦设置好,您可能会尝试执行以下操作:
但是在遍历列表的同时编辑它是一个badidea。相反,您可以在副本上迭代:
瞧,它起作用了。但是,嘿,} 简单地说:
words
现在是一个集合了,那么为什么还要麻烦循环呢?您可以使用^{练习:如何避免将整个排列列表
myWords
同时保存在内存中再次感谢@Kos。我的解决方式有点不同。虽然它不是超级漂亮,它的工作。在部署过程中,我不得不将/usr/share/dict/words更改为包中包含的文件,但除此之外,它还可以工作。如果您喜欢anagrams.mnickey.com或者这里的回购github.com/mnickey/anagrams,您可以在这里看到它的作用
相关问题 更多 >
编程相关推荐