我正在尝试按照 docstring 中的描述创建此函数,但要么我只通过了第一个 doctest,要么因 IndexError: list index out of range 而失败。如果我能以某种方式在循环内再次增加循环计数器而不会超出范围,我觉得这种当前的方法会起作用。我试过了
def menu_is_boring(meals):
"""Given a list of meals served over some period of time, return True if the
same meal has ever been served two days in a row, and False otherwise.
>>> menu_is_boring(['Egg', 'Spam'])
False
>>> menu_is_boring(['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam'])
True
"""
for i in range(len(meals)):
x = (meals[i] == meals[i+1]) and (meals[i] == meals[i+2])
return x
为了解决索引错误,我尝试使用 while 循环,但由于语法错误而失败:
for i in range(len(meals)):
x = (meals[i] == meals[(while i<len(meals): i+=1 )]) and (meals[i] == meals[while i<len(meals):i+=2])
嵌套循环会以某种方式工作还是我过度复杂化了?
PS 这个问题有可用的解决方案,但我想看看我的方法有什么问题或得到提示,而不是直接跳到解决方案。这是我的第一个问题,所以如果它没有遵循所有准则,请原谅。