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)
哇,謝謝。這確實提高了性能!非常感謝。 – LarmadVara