You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何无pass实现is_valid_word函数并避免多重else语句?

问题解答

1. 无需pass的实现方式

当然可以,把判断逻辑反过来就行:一旦发现不符合条件的情况就直接返回False,如果循环完整执行完毕没有触发返回,就说明所有字母都满足要求,全程不需要pass。

另外可以利用辅助函数get_frequency_dict直接生成hand的频率字典,比原代码复制字典再逐个检查的方式更简洁高效,还不会修改原hand:

def is_valid_word(word, hand, word_list):
    word = word.lower()
    word_freq = get_frequency_dict(word)
    hand_freq = get_frequency_dict(hand)
    
    if word not in word_list:
        return False
    
    # 遍历单词的每个字母及其需要的数量
    for char, needed_count in word_freq.items():
        # 如果hand里该字母数量不足,直接返回False
        if hand_freq.get(char, 0) < needed_count:
            return False
    
    # 所有检查通过,返回True
    return True

2. 避免多个else语句

用提前返回的思路就能实现:先把所有不符合条件的情况逐个处理并返回False,剩下的逻辑自然就是符合要求的场景,完全不需要嵌套的else。

优化后的完整代码如下:

def get_frequency_dict(sequence):
    freq = {}
    for x in sequence:
        freq[x] = freq.get(x, 0) + 1
    return freq

def is_valid_word(word, hand, word_list):
    word = word.lower()
    word_freq = get_frequency_dict(word)
    hand_freq = get_frequency_dict(hand)
    
    # 先检查单词是否在词库中,不在直接返回False
    if word not in word_list:
        return False
    
    # 检查每个字母的数量是否足够,不够直接返回False
    for char, needed in word_freq.items():
        if hand_freq.get(char, 0) < needed:
            return False
    
    # 所有条件都满足,返回True
    return True

这种写法让代码结构更扁平,逻辑链条更清晰,可读性更强。


内容的提问来源于stack exchange,提问作者Aja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:35:14