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

编写Lab04_yourname_module.py模块及指定函数的任务咨询

完成Lab04模块的具体操作步骤

一、创建模块文件

  • 新建Python文件,命名为Lab04_yourname_module.py(将yourname替换为你的实际名字)

二、实现containsLetter()函数

  • 参数定义:接收两个参数——word(待检查的目标字符串)和ch(需要查找的字符)
  • 核心逻辑:使用for循环遍历word中的每一个字符,逐一与ch对比
  • 返回规则:遍历过程中找到匹配字符则返回True;遍历结束未找到匹配则返回False
  • 细节提示:建议统一转换为小写(或大写)后再比较,避免大小写差异导致的判断错误,比如将word.lower()和ch.lower()用于循环对比

三、实现ruleChecker()函数

  • 参数定义:接收一个参数sentence(待检查的完整句子)
  • 执行步骤:
    1. 分割句子为单词列表:用sentence.split()方法将句子按空格拆分成单词数组,得到每个单词的索引(从0开始)
    2. 定义字母表:创建字符串alphabet = "abcdefghijklmnopqrstuvwxyz",通过索引直接获取对应位置的字母
    3. 遍历检查每个单词:
      • 对每个索引i,取出对应单词current_word和字母表中第i个字母target_char
      • 调用containsLetter()函数,检查当前单词是否包含目标字母(注意统一大小写)
      • 若发现某个单词不满足规则,立即返回该单词的索引i
    4. 全局验证通过:如果所有单词都符合规则,返回-1
  • 注意事项:如果句子单词数量超过字母表长度(26个),超出部分的单词没有对应字母,直接返回该单词的索引

四、测试验证(可选)

  • 在模块末尾添加测试代码,验证函数功能是否正常:
    if __name__ == "__main__":
        # 测试containsLetter函数
        print(containsLetter("bear", "b"))       # 预期输出:True
        print(containsLetter("bear", "x"))       # 预期输出:False
        print(containsLetter("Any", "a"))        # 预期输出:True(大小写兼容)
    
        # 测试ruleChecker函数
        valid_sentence = "A bear can discover precious food disguised beneath ice."
        print(ruleChecker(valid_sentence))       # 预期输出:-1
    
        invalid_sentence = "A beautifully crafted diamond necklace for girl was gifted by the groom."
        print(ruleChecker(invalid_sentence))     # 预期输出:7
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 21:55:19