Skip to main content
 首页 » 编程设计

Python之整理代码之循环和递归特性

2025年05月04日33jirigala

我有以下代码可以正常工作。然而,在我学习的同时,我正在努力寻找不断改进我的代码的方法。 是否有可能以任何方式使下面的代码更整洁?

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) 

请您参考如下方法:

使用 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) 查找时间。