-2

first of all I am sorry if this have been answered elsewhere. But I have been trying to solve this issue where I want to get the index where n elements repeats it self. So for example if I wanted the index from a list containing bools where True have repeated itself 3 times:

A = [False, False, True, True, True, False, True, True, True]

So in this example I would want the index 2.

3 Answers3

0

There are many ways to do this. Here's one:

A = [False, False, True, True, True, False, True, True, True]

def findSequence(lst, v, n):
    offset = 0
    while offset < len(lst) - n:
        try:
            i = lst[offset:].index(v)
            offset += i
            if lst[offset:offset+n].count(v) == n:
                return offset
            offset += 1
        except IndexError:
            break


print(findSequence(A, True, 3))

Output:

2
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
0

You can iterate over the list and increment a counter if the current element is equal to the previous one. If your counter becomes n, you can calculate the index easily:

def find(lst, n: int):
    counter = 1
    previous = None

    for index, element in enumerate(lst):
        if element == previous:
            counter += 1
        else:
            counter = 1

        if counter == n:
            return index - n + 1

        previous = element

    return -1

Output:

A = [False, False, True, True, True, False, True, True, True]
print(find(A, 3))

-> 2
Alex R
  • 3,139
  • 1
  • 18
  • 28
-1

Heres another approach.

def get_index(lst, n):
    for i in range(len(lst)):
        if lst[i:i+n] == [True]*n:
            return i
    return -1

Usage is basically print(get_index(lst, 3)) returns index if found, else returns -1. You could of course modify True to be any value you want to match against.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    This will work for the specific question being asked. However, it's woefully inefficient. You will potentially iterate more times than necessary and you'll be constructing a new list ([True]*n) for every iteration. However, it has been accepted as a viable answer so I guess you gain some kudos – DarkKnight Mar 12 '22 at 11:39