0

对不起,如果我张贴在错误的论坛上,但有什么办法来改善我的代码以多线程,进程或其他改进运行更快?Python使用多线程优化?

这个脚本的目的是根据你输入的单词为拼字游戏找到所有可能的单词并计算它的拼字比分。

当我输入一个超过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

变化WORDS = []set()

WORDS = set() 

然后改变方法将单词添加到它:

从:

WORDS.append(line.rstrip().lower()) 

到:

WORDS.add(line.rstrip().lower()) 

没有理由为此使用列表。这应该会提高性能。

+0

哇,谢谢。这确实提高了性能!非常感谢。 – LarmadVara