Home > OS >  Python: Finding neighbouring duplicates in a list
Python: Finding neighbouring duplicates in a list

Time:12-21

First things first...I am Python newbie...so I apologize, if this is maybe the most basic question you have ever seen here. Fundamentally, I want to solve a question from a Kaggle Python (beginner) course to solve the following challenge:

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.
    """    

I created the following nested for loop. The idea was that I can compare this way the list to itself and the moment I find a duplicate it returns true:

for i in range(len(meals)):
        for j in range(i 1, len(meals)):
            if j == i:
                return True
    return False

The input is: meals=['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']

So I would anticipate a "True" (2X Spam in a row), but my function returns a False. It looks sooo easy..but apparently I am missing something. Maybe there is something fundamental about nested loops that I am missing here. I googled other problems where nested loops are used for duplicated...but cant see an obvious difference to what I did.

CodePudding user response:

An easier solution is to just use one loop and use i 1 as your second index, but note that you have to reduce the length of your loop, because otherwise you get out of bound at the last loop cycle.

for i in range(len(meals) - 1):
    if meals[i] == meals[i   1]:
        return True
# iff no same meals at two days the loop doesnt return True
# and after loop is finished execute next code, which is return False
return False

CodePudding user response:

Another way to handle this is to use the zip() function to tie the original list to an 1-offset of the original list and compare the values as if a == b.

For example:

def test(items: list):
    return any(a==b for a, b in zip(items, items[1:]))

This builds a generator expression of boolean values. The any() function will 'short circuit' and return immediately once a True value is found; thus making this function quite efficient.

Output:

>>> meals = ['Spam', 'Eggs', 'Spam', 'Spam', 'Bacon', 'Spam']
>>> test(meals)

True
  • Related