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

Python自定义Dict类is_known方法多单词匹配异常问题

问题:添加多个词后Dict类的is_known方法失效

需求回顾

  • VerbWord和NounWord类分别接收动词原型、名词单数作为构造参数,实现get_forms()方法返回对应词的所有形式:动词包含原形、加s、ing、ed/d(结尾为e时加d);名词包含单数、加s。
  • Dict类通过实例变量words存储词对象,提供add_word方法添加词对象,is_known方法判断输入字符串是否为词典中任意词的任意形式。

问题现象

单个词添加时功能正常,但添加多个词后is_known方法失效:测试用例中添加NounWord('star')和NounWord('create')后,调用dict.is_known('create')返回False,预期结果为True。

用户代码

class VerbWord:
  def __init__(self,verb):
    self.verb = verb
  def get_forms(self):
    listOfForms = []
    listOfForms.append(self.verb)
    listOfForms.append(self.verb+"s")
    listOfForms.append(self.verb+"ing")
    if self.verb[-1] == "e":
      listOfForms.append(self.verb+"d")
    else:
      listOfForms.append(self.verb+"ed")
    return listOfForms
    
class NounWord:
  def __init__(self,noun):
    self.noun = noun
  def get_forms(self):
    listOfForms = []
    listOfForms.append(self.noun)
    listOfForms.append(self.noun+"s")
    return listOfForms

class Dict:
  def __init__(self):
    self.words = []
    
  def add_word(self,word):
    self.words.append(word)
 
  def is_known(self,word):
    for w in self.words:
      a = w.get_forms()
      if word in a:
        return True
      else:
        return False

测试用例

dict = Dict()
dict.add_word(NounWord("star"))
print(dict.is_known("stars"))
dict.add_word(NounWord("create"))
print(dict.is_known("create"))

输出对比

  • 预期输出:
    True
    True
    
  • 实际输出:
    True
    False
    

问题原因

Dict类的is_known方法逻辑错误:循环检查第一个词时,若输入字符串不在该词的形式列表中,会直接返回False,不会继续检查后续添加的词对象。比如测试用例中,检查create时,第一个词是star,create不在star的形式里,方法直接返回False,完全没处理第二个create词对象。

修复方案

修改is_known方法,仅当遍历完所有词对象都未找到匹配时,才返回False;找到匹配则立即返回True。

修复后的Dict类代码:

class Dict:
  def __init__(self):
    self.words = []
    
  def add_word(self,word):
    self.words.append(word)
 
  def is_known(self,word):
    for w in self.words:
      a = w.get_forms()
      if word in a:
        return True
    # 遍历完所有词都没匹配才返回False
    return False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:10:47