对不起,如果我在错误的论坛上发帖,但有没有办法改进我的代码,以便在多线程,流程或其他改进中更快地运行?
此脚本的目的是根据您输入的单词找到拼字游戏的所有可能单词并计算它的拼字游戏分数。
当我输入一个超过7个字符的单词时,需要永远进行计算。
scores = {"a": 1, "c": 3, "b": 3, "e": 1, "d": 2, "g": 2,
"f": 4, "i": 1, "h": 4, "k": 5, "j": 8, "m": 3,
"l": 1, "o": 1, "n": 1, "q": 10, "p": 3, "s": 1,
"r": 1, "u": 1, "t": 1, "w": 4, "v": 4, "y": 4,
"x": 8, "z": 10}
WORDS = []
combs = dict()
def prepareDict(file):
try:
f = open(file, 'r')
for line in f:
WORDS.append(line.rstrip().lower())
except OpenErrors:
print("Could not open file")
finally:
f.close()
def combinations(word):
for i in range(len(word)+1):
combList = itertools.permutations(word, i)
for item in combList:
item = ''.join(item)
if item in WORDS:
value = 0
for c in item:
value += int(scores.get(c))
combs[item] = value
return (combs)
if __name__ == "__main__":
prepareDict('sowpods.txt')
if len(sys.argv) > 2 or len(sys.argv) < 2:
print("usage: %s <word>" % sys.argv[0])
sys.exit(1)
else:
word = sys.argv[1].lower()
combs = combinations(word)
sorted_combs = sorted(combs.items(), key=operator.itemgetter(1), reverse=True)
for word in sorted_combs:
print(word)
答案 0 :(得分:0)
将WORDS = []
更改为set()
:
WORDS = set()
然后更改方法以向其添加单词:
从:
WORDS.append(line.rstrip().lower())
为:
WORDS.add(line.rstrip().lower())
没有理由使用列表。这应该可以提高性能。