lax123
lax123

Reputation: 21

How to find a duplicate of a list that repeats three times in a row

Given a list of duplicate numbers, how to find a number that repeats three times in a row. For example:

l1 = [1,1,2,2,3,3,3,4,4]

I want to print element number 3 as it appears three times in a row.

I have tried using Counter, which converts this to dict, but not sure how to just print the key that as the max count value.

Upvotes: 1

Views: 1429

Answers (2)

jpp
jpp

Reputation: 164673

Using a list comprehension with zip:

L = [1,1,2,2,3,3,3,4,4]

res = [i for i, j, k in zip(L, L[1:], L[2:]) if i == j == k]  # [3]

Generalised for an arbitrary number of repeats, you can use list slicing:

n = 3
res = [L[idx] for idx in range(len(L)-n) if len(set(L[idx: idx+n])) == 1]  # [3]

Upvotes: 2

Herc01
Herc01

Reputation: 632

Here, Easy. That should help:

d={i:L.count(i) for i in L if L.count(i)>2}

This return a dict with the number that are repeated more than2 times.In your case:

{3: 3}

Upvotes: 0

Related Questions