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

Python中如何校验字符串仅由指定列表字母构成并移除已用字母

现有代码问题梳理
  1. 语法错误:方法定义行末尾缺少冒号
  2. 逻辑只校验了word的第一个字符,遍历到第一个字符存在就直接返回True,没有检查后续所有字符
  3. 没有处理重复字母的数量匹配规则,仅判断字符是否存在,不校验数量是否满足word的重复要求
  4. 完全没有实现校验通过后移除已使用字母的逻辑
功能实现代码
class WordChecker:
    def __init__(self, letters):
        self.letters = letters
    
    def wordcheck(self, word):
        # 临时复制列表做校验,避免校验失败时污染原列表
        temp = self.letters.copy()
        for char in word:
            if char in temp:
                temp.remove(char)
            else:
                return False
        # 全部校验通过,更新原列表
        self.letters = temp
        return True
测试示例
# 初始化参数
letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
w = WordChecker(letters)

print(w.wordcheck('feed')) # 输出 False,e的数量只有2个,满足不了feed需要的3个
print(w.wordcheck('gag')) # 输出 False,g只有1个,满足不了gag需要的2个
# 重置letters后再次测试
w.letters = ['n', 'e', 'f', 'g', 'e', 'a', 'z']
print(w.wordcheck('gene')) # 输出 True
print(w.letters) # 输出 ['f', 'a', 'z']

注:你给出的示例中连续两次调用w.wordcheck('gene')都返回True属于笔误,第一次调用已经把gene需要的g、n、两个e全部移除,第二次调用时字母不足会返回False。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:09:02