【发布时间】:2012-04-22 07:52:39
【问题描述】:
基本上,我有一个 Python 脚本,它需要几个字母,获取它们的每个组合,然后检查它是否是一个实际的单词(以某种方式思考拼字游戏)但由于某种原因它多次返回相同的单词,我不想这样做,脚本看起来像:
with open("dictionary.txt") as word_file:
english_words = set(word.strip().lower() for word in word_file)
def is_english_word(word):
return word.lower() in english_words
print is_english_word("ham")
print is_english_word("zz")
a = raw_input("Please enter first letter: ")
b = raw_input("Please enter second letter: ")
c = raw_input("Please enter third letter: ")
d = raw_input("Please enter fourth letter: ")
e = raw_input("Please enter fifth letter: ")
check =[a,b,c,d,e]
def get_combos(list):
import itertools
count = len(list)
got = []
combos =[]
while count > 0:
for a in itertools.permutations(list,count):
if a in got:
got.append(a)
else:
got.append(a)
combos.append(a)
count = count - 1
for a in combos:
strip_combos(a)
def strip_combos(list):
count = ''
words = []
for entry in list:
count = count + entry
words.append(count)
check_combo(words)
def check_combo(list):
words = []
got = []
for entry in list:
if is_english_word(entry):
if entry not in words:
print entry
words.append(entry)
get_combos(check)
现在它也可以按我的意思工作,只打印字典中的单词,但它会多次打印同一个单词,例如,如果字母是:
a、c、e、s
它会在每次显示在列表中时返回,但据我所知,我通过 got 和 words 列表省略了在 check_combo 过程中多次出现的相同结果
我觉得这个问题可能源于 while 循环中的 get_combos 过程,尽管我尝试修改几乎所有内容都无济于事,所以我转向那些比我更有知识的人寻求帮助。
【问题讨论】:
-
一些文档字符串/cmets 可能会有所帮助。例如,strip_combos 应该做什么完全不清楚。
-
字符串已经是可迭代的。无需将其转换为列表。不要单独询问每个字母,而是:
check = raw_input("Please enter 5 letter word: ")