Wednesday, February 21, 2024
HomeSoftware EngineeringOrdered Rely of Characters in Python

Ordered Rely of Characters in Python


The problem

Rely the variety of occurrences of every character and return it as a listing of tuples so as of look. For empty output return an empty record.

Instance:

ordered_count("abracadabra") == [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]

The answer in Python code

Possibility 1:

from collections import Counter
def ordered_count(enter):
    c = Counter(enter)
    return sorted(record(c.gadgets()), key=lambda x: enter.index(x[0]))

Possibility 2:

def ordered_count(_input):
    l = []
    for i in _input:
        if i not in l:
            l.append(i)
    return [(i, _input.count(i)) for i in l]

Possibility 3:

def ordered_count(inp):
    return [(i, inp.count(i)) for i in sorted(set(inp), key=inp.index)]

Take a look at instances to validate our resolution

take a look at.describe("Primary Exams")

checks = (
    ('abracadabra', [('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)])
)

for t in checks:
    inp, exp = t
    take a look at.assert_equals(ordered_count(inp), exp)

take a look at.describe("Random Exams")
def random_tests():
    from string import (
        ascii_letters,
        punctuation,
        digits
    )

    from collections import (
        OrderedDict,
        Counter
    )

    from random import (
        randint,
        alternative
    )

    class _OrderedCounter(Counter, OrderedDict):
        cross
    
    
    def reference(seq):
        return record(_OrderedCounter(seq).gadgets())
    
    
    CHARS = "".be a part of(("     ", ascii_letters, punctuation, digits))
    
    for _ in vary(100):
        test_case = "".be a part of(alternative(CHARS) for _ in vary(randint(1, 1000)))
        take a look at.assert_equals(ordered_count(test_case), reference(test_case))
        
random_tests()
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments