首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么自动平地机给我的CodeHS 8.4.9:猫头鹰第2部分的错误?

为什么自动平地机给我的CodeHS 8.4.9:猫头鹰第2部分的错误?
EN

Stack Overflow用户
提问于 2020-11-02 09:55:06
回答 1查看 728关注 0票数 0

任务如下:

这个程序是你以前的“猫头鹰”计划的扩展。除了报告包含单词owl的单词数量外,您还应该报告单词发生的索引!下面是运行程序的示例可能是什么样子:

代码语言:javascript
复制
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”的单词的索引。枚举函数也会派上用场!

下面是我的代码:

代码语言:javascript
复制
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))

当我运行代码时,它是非常好的。但是当它必须通过自动平平机时,它说我做错了事情。这个输入让我犯的错误最少。下面是一些我以前使用过的,如果有用的话:

猫头鹰是小猫头鹰。小孔雀被称为桃子。猫头鹰真酷!我想下雪的猫头鹰可能是我的最爱。也可能是斑点猫头鹰。我觉得猫头鹰很酷

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

第一部自动平地机图片

第二自动平地机图片

第三自平机图片

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-02 10:27:33

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

我认为最大的问题是,您的代码打印计数行,然后返回索引行。如果自动平平器只执行您的函数并忽略返回值,它将忽略索引。请注意,您引用的示例代码会打印两行,并且不会返回任何内容。以下版本对此作了更正。

注意,这段代码使用枚举--如果您需要列表的内容,并且需要跟踪列表中的索引,那么养成使用它的习惯是一个非常好的函数。

代码语言:javascript
复制
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循环--所以更好的版本应该是:

代码语言:javascript
复制
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))

更新- 02/11/2020 - 14:12 -预期的结果,从自动平平器预期引号周围的‘猫头鹰’在第一个输出消息。上述代码已被更新,以包括这些引号。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64643278

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档