Viper
Viper

Reputation: 121

How to check if a number has occurred a particular number of times in a list consecutively

I am given a list:

[1 , 0 , 4 , 4 , 4 , 4 , 4 , 1]

I want to write a program that checks if there exists a number in my list that occurs 5 times (number may vary depending on user input) consecutively and return that number.

In this case the output should be 4.

Are there any predefined functions in Python that solve such problems?

Upvotes: 3

Views: 91

Answers (4)

ComplicatedPhenomenon
ComplicatedPhenomenon

Reputation: 4189

Sliding window for this problem.

def checkList(listi, num):
    k = [listi[0]]
    nk = 0
    listo = []
    for v in listi[1:]:
        if v == k[-1]:
            k.append(v)
        else:
            if len(k) == num:
                listo.append(k[-1])
            k = [v]
    if len(k) == num:
        listo.append(k[-1])
    return listo

l = [1 , 0 , 4 , 4  ,4, 4 , 4 , 1]
print(checkList(l, 5))

Upvotes: 0

Georgina Skibinski
Georgina Skibinski

Reputation: 13387

y=list(set([x[i-1] for i in range(n-1, len(x)) if x[i-n:i]==[x[i-n]]*n]))

Where
n - number of consecutive occurrences you are looking for
x - list, which you input
y - list of elements that occur consecutively n times

Upvotes: 0

Delgan
Delgan

Reputation: 19617

You can make use of itertools.groupby() like this:

from itertools import groupby
lst = [1 , 0 , 4 , 4 , 4 , 4 , 4 , 1]

for number, sublist in groupby(lst):
    if len(list(sublist)) == 5:
        print(number)

By default, groupby() groups continuous elements based on equality, so it works perfectly fine for you (otherwise, the key argument can be provided).

While iterating through lst, the groupby() function will construct a new sub-list and populate it with all consecutive values equals to each other. If the iterated value differs from the previous one, groupby() will yield the number with the corresponding sublist populated. That is: (1, [1]), (0, [0]), (4, [4, 4, 4, 4, 4]) and finally (1, [1]). So, you just have to check the len() of the yielded sublist to verify it contains enough elements. Note that those are not actually "list" but rather "iterable", hence the required call to list().

Upvotes: 4

U13-Forward
U13-Forward

Reputation: 71560

Try this list comprehension:

print([v for i, v in enumerate(lst, 1) if {v} == set(lst[i:i+4])])

Output:

[4]

Upvotes: 0

Related Questions