0

what would be a simple way for finding and outputting a row of repeating integers in an array

For example, an array of 1 2 3 4 4 4 5 6 should output 4 4 4

2 Answers2

0

There's quite a few ways to answer the question with different outputs for corner cases, but how about this for a minimal example that solves the specifically mentioned case correctly?

x = [1, 2, 3, 4, 4, 4, 5, 6]
ind = [a==b for a,b in zip(x[:-1],x[1:])].index(True)
y = [a for a in x if a==x[ind]]
print(y)

gives [4, 4, 4]

Brian
  • 1,988
  • 1
  • 14
  • 29
0

The code below will make a list of sequence lists of all repeating items.

list = [1, 2, 3, 4, 4, 4, 5, 6, 6, 7, 8, 8, 8, 8, 3, 4, 2, 3, 3]

last = None
sequences = []
series = []
list.append('last')
for item in list:
    if item == last:
        series.append(last)
    elif series:
        series.append(last)
        sequences.append(series)
        series = []
    last = item
if series:
    series.append(last)
    sequences.append(series)
print sequences

Will output

>>> [[4, 4, 4], [6, 6], [8, 8, 8, 8], [3, 3]]
RFV
  • 831
  • 8
  • 22