我有以下代码可以正常工作。然而,虽然我正在学习我试图找到不断改进我的代码的方法。 是否可以以任何方式使下面的代码更整洁?
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
"""
x=''
if word in wordList:
x=True
else:
x=False
#dont mutate the hand so copy
hand2=hand.copy()
for letter in word:
if letter in hand2.keys():
hand2[letter]-=1
if hand2[letter]<0:
x=False
break
else:
x = False
return x
运行代码:
hand = {'r': 1, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1}
word = "rapture"
wordList = ['rapture','alex']
isValidWord(word, hand, wordList)
答案 0 :(得分:3)
使用all
和Counter
:
from collections import Counter
def isValidWord(word, hand, wordList):
wc = Counter(word)
return word in wordList and all(wc[c] <= hand.get(c, -1) for c in wc)
如果您有非常大的单词列表,请考虑使用集合代替O(1)查找时间。
答案 1 :(得分:2)
正确处理计数:
from collections import Counter
def isValidWord(word, hand, wordList):
# Check for membership first and early out if fails
# Otherwise, see if the count of any letter in word exceeds that of the hand
return word in wordList and all(hand.get(let, -1) >= cnt for let, cnt in Counter(word).items())