이 글을 잘못된 포럼에 게시하면 미안하지만 다중 스레드, 프로세스 또는 기타 개선 사항으로 더 빠르게 실행되도록 코드를 개선 할 수있는 방법이 있습니까?
이 스크립트의 목적은 입력 한 단어를 기반으로 스크래블 게임에 가능한 모든 단어를 찾아서 스크래블 점수를 계산하는 것입니다.
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)
변경 WORDS = []
로 set()
:
WORDS = set()
그런 다음 단어를 추가하는 방법을 변경하십시오.
에서:
WORDS.append(line.rstrip().lower())
에:
WORDS.add(line.rstrip().lower())
목록을 사용할 이유가 없습니다. 이렇게하면 성능이 향상됩니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다