pythonarrayslistindexingboolean

index/array troubleshooting : homework


this code:

"""this is a simple empty template in which to experiment"""
menu = ['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']

def 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.
    """
    return [
        (
            i[meals.index(i)] == i[(meals.index(i) + 1)]
            )
            for i in meals if meals.index(i) < (len(meals)-1)
    ]

# This is the end of the doc
print(
    boring(menu)
)

Keeps throwing this error code:

File "c:\work\Tester.py", line 10, in <listcomp>
    i[meals.index(i)] == i[(meals.index(i) + 1)]
                         ~^^^^^^^^^^^^^^^^^^^^^^
IndexError: string index out of range

I'm trying to avoid having to use normal conditionals or loops and stick with comprehensions. It would just be in keeping to the unspoken goals the course has for each student.

Is this impossible without expanding past a single comprehension?


Solution

  • The issue in your code is that you are using the index of the meal i as the index to access elements in i. This can lead to an IndexError because the index is an integer, but i is a string (a meal in this case). In a list comprehension, you should iterate directly over the elements, not their indices.

    Here's a corrected version of your code using a list comprehension:

    menu = ['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']
    
    
    def 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.
    """
    return any(meals[i] == meals[i + 1] for i in range(len(meals) - 1))
    

    In this version, any is used to check if there is any pair of consecutive days with the same meal. The list comprehension iterates over the indices of meals, and meals[i] == meals[i + 1] checks if the meal on day i is the same as the meal on the next day (i + 1). This avoids the use of indices directly on the meal strings.

    This should give you the desired result without expanding past a single comprehension.