簡體   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