简体   繁体   中英

Incrementing Python loop counter inside the loop without IndexError: list index out of range

I am trying to create this function as described in docstring but either I get just 1st doctest passed or fail with IndexError: list index out of range. I feel this current approach will work if somehow I can increment the loop counter again inside the loop without falling off range. I tried

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

To solve the Index error I tried using while loop but that fails with syntax error:

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])

Will a nested loop somehow work or am I over complicating this?

PS There is solution available to the problem but I am trying to see what is wront with my approach or get a hint, instead of jumping to the solution directly. This my 1st question so please excuse me if it is not following all the guidelines.

Just remember the last meal:

def menu_is_boring(meals):
    last = None
    for meal in meals:
        if meal == last:
            return True
        last = meal
    return False

It looks like you're checking for 3 days in a row with x = (meals[i] == meals[i+1]) and (meals[i] == meals[i+2]) . Also, the IndexError is caused by the fact that you're trying to access the n+1th and n+2th elements of a list with n elements. To avoid that, you should run the loop till n-1 or n-2 as necessary.

So all you have to do is:

for i in range(len(meals)-1):  # Run the loop till n-1
    x = meals[i] == meals[i+1] # Check for nth and n+1th meal to be same
return x

Having said that, this section will not solve your problem, and will always return the value for the last meal pair, since x is getting overwritten on every iteration of the loop. To solve that, you can return a True as soon as you find a repetition.

def menu_is_boring(meals):
    for i in range(len(meals)-1):
        if meals[i] == meals[i+1]:
            return True
    return False

You can test it by calling the function and printing its return value.

print (menu_is_boring(['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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