'Finding index where n elements equal in Python
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.
Solution 1:[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.
Solution 2:[2]
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
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 | Albert Winestein |
| Solution 3 | Alex R |
