Software Engineering

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]

The solution in Python code

Option 1:

def unique_in_order(iterable):
    result = []
    prev = None
    for char in iterable[0:]:
        if char != prev:
            prev = char
    return result

Option 2:

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

Option 3:

from itertools import groupby

def unique_in_order(iterable):
    return [x for (x, _) in groupby(iterable)]

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('AAAABBBCCDAABBB'),['A', 'B', 'C', 'D', 'A', 'B'])
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")