のより速いバージョンを提供してください。compChooseWord(hand、wordList、n)関数。 ここにいくつかの詳細があります。どうすればコンピュータが単語リストから83667語の単語をすばやく選択できるようにすることができますか?
wordListは83667語のリストです。
手は{ 'A':1、 'P':2 'S':1、 'E':1、 'L':1}
nは正の整数
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
def getWordScore(word, n):
score=0
for i in word:
if i in SCRABBLE_LETTER_VALUES:
score=score+SCRABBLE_LETTER_VALUES[i]
score=score*len(word)
if len(word)==n:
score=score+50
return score
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
c=True
wordCount=len(word)
handCopy=hand.copy()
for i in word:
if i in hand:
handCopy[i]=handCopy.get(i,0)-1
wordCount=wordCount-1
if handCopy[i]<0:
c=False
break
b=word in wordList and wordCount==0
return b and c
上記@mromanコメントを1として機能
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand: dictionary (string -> int)
wordList: list (string)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: string or None
"""
bestScore = 0
bestWord = None
for word in wordList:
if isValidWord(word, hand, wordList):
score = getWordScore(word, n)
if (score > bestScore):
bestScore = score
bestWord = word
return bestWord
これは宿題のように聞こえる...この家庭は仕事ですか?あなたはそれをより速くしようとしましたが、結果は何でしたか?現在のパフォーマンスはどれくらい悪いですか? – SaggingRufus
1つの簡単なことは、wodlistをスコア順に並べ替えることです。そうすれば、有効な単語が見つかるとすぐにループを止めることができます。 – mroman