【发布时间】:2017-02-21 11:08:51
【问题描述】:
提供 compChooseWord(hand, wordList, n) 函数的更快版本。 这里有一些细节。
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
为以下功能提供替代更快的版本
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
【问题讨论】:
-
这听起来像是家庭作业...这是家庭作业吗?你有什么尝试让它更快,结果是什么?目前的表现有多差?
-
一个简单的事情就是按分数对 wodlist 进行排序。这样一来,您就可以在找到有效单词后立即停止循环。
标签: performance function python-3.x loops data-structures