luckiblue
luckiblue

Reputation: 11

Constant subsequence from given sequence of numbers in python

Hi I want to get a subsequence of the same numbers from given sequence. The subsequences should be returned as list.

For example

input = [4, 5, 67, 2, 4, 4, 4, 6, 2, 2, 3]

and

output = [ [4, 4, 4], [2, 2] ].

I have a problem with for loop because when I compare two elements of list e.g:

for i in seq:
       if i == seq[i+1]

I'm getting a list index out of range error. I know it isn't complicated but I'm just getting started with programming.

Upvotes: 1

Views: 658

Answers (2)

Iftekhar Uddin Ahmed
Iftekhar Uddin Ahmed

Reputation: 589

You can use groupby of itertools here

import itertools

input = [4, 5, 67, 2, 4, 4, 4, 6, 2, 2, 3]
list_of_sequence_list = [list(group) for key, group in itertools.groupby(input)]
subsequence_list = [sequence_list for sequence_list in list_of_sequence_list if len(sequence_list)>1]

print subsequence_list

Upvotes: 1

levi
levi

Reputation: 22697

When your loop reaches the last element in the array, in your example 3, you are trying to get the "next element" seq[i+1] but there is no one, because 3 is the last one.

So, you can try to check if there is a next element.

for i in seq:
       next = seq[i+1] if i < len(seq) else None
       if next and i ==  next

Upvotes: 1

Related Questions