Sunday, February 26, 2023
HomeSoftware EngineeringOrdered Depend of Characters in Python

Ordered Depend of Characters in Python


The problem

Depend the variety of occurrences of every character and return it as an inventory of tuples so as of look. For empty output return an empty checklist.

Instance:

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

The answer in Python code

Choice 1:

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

Choice 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]

Choice 3:

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

Check circumstances to validate our answer

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):
        go
    
    
    def reference(seq):
        return checklist(_OrderedCounter(seq).objects())
    
    
    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()

Previous articleIBPS Clerk Follow Paper
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments