Skip to content

Unique In Order in Python

The challenge

Implement the function unique_in_order which takes as argument a sequence and returns a list of items without any elements with the same value next to each other and preserving the original order of elements.

For example:

unique_in_order('AAAABBBCCDAABBB') == ['A', 'B', 'C', 'D', 'A', 'B'] unique_in_order('ABBCcAD') == ['A', 'B', 'C', 'c', 'A', 'D'] unique_in_order([1,2,2,3,3]) == [1,2,3]
Code language: Python (python)

The solution in Python code

Option 1:

def unique_in_order(iterable): result = [] prev = None for char in iterable[:]: if char != prev: result.append(char) prev = char return result
Code language: Python (python)

Option 2:

def unique_in_order(iterable): r = [] for x in iterable: x in r[-1:] or r.append(x) return r
Code language: Python (python)

Option 3:

from itertools import groupby def unique_in_order(iterable): return [x for (x, _) in groupby(iterable)]
Code language: Python (python)

Test cases to validate our solution

test.describe("lets test it")"should work with empty array") test.assert_equals(unique_in_order(''),[])"should work with one element") test.assert_equals(unique_in_order('A'),['A'])"should reduce duplicates") test.assert_equals(unique_in_order('AA'),['A']) test.assert_equals(unique_in_order('AAAABBBCCDAABBB'),['A', 'B', 'C', 'D', 'A', 'B']) test.assert_equals(unique_in_order('AADD'),['A','D']) test.assert_equals(unique_in_order('AAD'),['A','D']) test.assert_equals(unique_in_order('ADD'),['A','D'])"and treat lowercase as different from uppercase") test.assert_equals(unique_in_order('ABBCcAD'),['A', 'B', 'C', 'c', 'A', 'D'])"and work with int arrays") test.assert_equals(unique_in_order([1,2,3,3]),[1,2,3])"and work with char arrays") test.assert_equals(unique_in_order(['a','b','b']),['a','b'])
Code language: Python (python)

See also  How to use forEach method in Javascript
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x