Wednesday, February 21, 2024
HomeSoftware EngineeringDistinctive In Order in Python

Distinctive In Order in Python


The problem

Implement the perform unique_in_order which takes as argument a sequence and returns an inventory of things with none components with the identical worth subsequent to one another and preserving the unique order of components.

For instance:

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 answer in Python code

Choice 1:

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

Choice 2:

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

Choice 3:

from itertools import groupby

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

Take a look at instances to validate our resolution

take a look at.describe("lets take a look at it")
take a look at.it("ought to work with empty array")
take a look at.assert_equals(unique_in_order(''),[])
take a look at.it("ought to work with one ingredient")
take a look at.assert_equals(unique_in_order('A'),['A'])
take a look at.it("ought to cut back duplicates")
take a look at.assert_equals(unique_in_order('AA'),['A'])        
take a look at.assert_equals(unique_in_order('AAAABBBCCDAABBB'),['A', 'B', 'C', 'D', 'A', 'B'])
take a look at.assert_equals(unique_in_order('AADD'),['A','D'])
take a look at.assert_equals(unique_in_order('AAD'),['A','D'])
take a look at.assert_equals(unique_in_order('ADD'),['A','D'])
take a look at.it("and deal with lowercase as totally different from uppercase")
take a look at.assert_equals(unique_in_order('ABBCcAD'),['A', 'B', 'C', 'c', 'A', 'D'])
take a look at.it("and work with int arrays")
take a look at.assert_equals(unique_in_order([1,2,3,3]),[1,2,3])
take a look at.it("and work with char arrays")
take a look at.assert_equals(unique_in_order(['a','b','b']),['a','b'])
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments