繁体   English   中英

为什么自动分级器给我关于 CodeHS 8.4.9: Owls Part 2 的错误?

[英]Why is the autograder giving me errors for CodeHS 8.4.9: Owls Part 2?

这是任务:

该计划是您之前的“猫头鹰”计划的扩展。 除了只报告包含单词 owl 的单词数量之外,您还应该报告单词出现的索引! 以下是您的程序运行示例:

Enter some text: Owls are so cool! I think snowy owls might be my favorite. Or maybe spotted owls.
There were 3 words that contained "owl".
They occurred at indices: [0, 7, 15]

从输出中可以看出,您必须使用另一个列表来存储找到包含“owl”的单词的索引。 枚举函数也可能派上用场!

这是我现在的代码:

def owl_count(text):
owl_lower = text.lower()
owl_split = owl_lower.split()
count = 0
index = 0
sec_in = []
owl = "owl"
for i in range(len(owl_split)):
    if owl in owl_split[index]:
        count = count + 1
        sec_in.append(index)
    index = index + 1
print("There were " + str(count) + " words that contained owl.")
return "They occurred at indices: " + str(sec_in)

text = "I really like owls. Did you know that an owl's eyes are more than twice as big as the eyes of other birds of comparable weight? And that when an owl partially closes its eyes during the day, it is just blocking out light? Sometimes I wish I could be an owl."
print(owl_count(text))

当我运行代码时,它完全没问题。 但是当它必须通过自动分级器时,它会说我做错了。 这个输入是什么让我的错误最少。 如果有帮助,以下是我以前使用过的一些:

猫头鹰是猫头鹰宝宝。 小孔雀被称为桃子。

猫头鹰太酷了! 我想雪鸮可能是我的最爱。 或者也许是斑点猫头鹰。

我觉得猫头鹰很酷

这是我用来帮助我的代码的链接。

第一张自动分级机图片

第二个自动分级机图片

第三个自动分级机图片

正如评论中提到的,您的代码有很多冗余变量 - 这是您的代码的整理版本 - 它应该与您的完全相同:

我认为最大的问题是您的代码打印计数行,然后返回索引行。 如果自动分级器只是执行您的函数并忽略返回值,它将忽略索引。 请注意,您引用的示例代码打印了两行 - 并且不返回任何内容。 这在下面的版本中得到纠正。

请注意,此代码使用 enumerate - 如果您需要列表的内容并且还需要跟踪列表中的索引,这是一个很好的函数,可以养成使用的习惯。

def owl_count(text):
    owl_lower = text.lower()
    owl_split = owl_lower.split()
    sec_in = []
    owl = "owl"
    for index, word in enumerate(owl_split):
        if owl in word:
           sec_in.append(index)
    print("There were " + str(len(sec_in)) + " words that contained \"owl\".")
    print("They occurred at indices: " + str(sec_in))

text = "I really like owls. Did you know that an owl's eyes are more than twice as big as the eyes of other birds of comparable weight? And that when an owl partially closes its eyes during the day, it is just blocking out light? Sometimes I wish I could be an owl."
owl_count(text)

有一个更有效的方法来解决这个问题,没有很多只用于创建其他变量的变量 - 而且你有一个 for 循环,它可以/应该是一种理解 - 所以一个更好的版本是:

def owl_count(text):
    sec_in = [index for index, word in enumerate(text.lower().split())
                      if 'owl' in word]
    print("There were " + str(len(sec_in)) + " words that contained \"owl".")
    print("They occurred at indices: " + str(sec_in))

更新 - 2020 年 2 月 11 日 - 14:12 - 自动分级器的预期结果需要在第一条输出消息中的“owl”一词周围加上引号。 上面的代码已更新以包含这些引号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM