I have a sequence like [0, 1, 0, 1, 0, 1, 0] and I need a function to remove repeated adjacent sequence pairs, keeping the first one, and return [0, 1, 0]. These are some results I expect.
>>> remove_repeated_pairs([0, 1])
[0, 1]
>>> remove_repeated_pairs([0, 1, 0])
[0, 1, 0]
>>> remove_repeated_pairs([0, 1, 0, 1])
[0, 1]
>>> remove_repeated_pairs([0, 1, 0, 1, 0])
[0, 1, 0]
>>> remove_repeated_pairs([2, 0, 1, 0, 1, 0])
[2, 0, 1, 0]
>>> remove_repeated_pairs([1, 2, 0, 1, 0, 1, 0])
[1, 2, 0, 1, 0]
first edition:
I tried this code:
def remove_repeated_pairs(seq):
result = []
for i in range(0, len(seq), 2):
if len(result) >= 2:
last_seq = result[-2:]
else:
last_seq = None
pair = seq[i:i + 2]
if pair != last_seq:
result.extend(pair)
return result
But it doesn’t works with this:
>>> remove_repeated_pairs([1, 3, 0, 2, 1, 2, 1, 3, 0])
[1, 3, 0, 2, 1, 2, 1, 3, 0]
The right answer should be [1, 3, 0, 2, 1, 3, 0]
I think that the issue comes from the fact that you go over the elements of your list 2 by 2 (for i in range(0, len(seq), 2).
So if a repeated pair starts on an odd place, you won’t detect it – as in the last example you give.
I would try something like:
Regards,