Question

return the top n most frequently occurring chars and their respective counts

e.g aaaaaabbbbcccc, 2 should return [(a 5) (b 4)]

in case of a tie, return char which comes earlier in alphabet ordering

e.g. cdbba,2 -> [(b,2) (a,1)]

here is my code regarding the concept:

def top_chars(word, n):
    import collections
    result=collections.Counter(word)
    key=result.keys()
    value=result.values()
    for  i in range(len(key)):
        for j in range(len(key)):
            if value[i]>value[j]:
                t=key[j]
                key[j]=key[i]
                key[i]=t
                v=value[j]
                value[j]=value[i]
                value[i]=v
    for  i in range(len(key)):
        for j in range(len(key)):
            if value[i]==value[j]:
                if key[i] < key[j]:
                    t=key[j]
                    key[j]=key[i]
                    key[i]=t
    k=zip(key,value)
    return k[0:n]
    pass

and the test cases are:

assert [('p', 2)] == top_chars("app",1)
assert [('p', 2), ('a',1)] == top_chars("app",2)
assert [('p', 2), ('a',1)] == top_chars("app",3)

assert [('a', 2)] == top_chars("aabc", 1)
assert [('a', 2), ('b', 1)] == top_chars("aabc", 2)
assert [('a', 2), ('b', 1), ('c', 1)] == top_chars("aabc", 3)

my question is to write the code without collections module

can anyone help me out of this.thanks in advance

Était-ce utile?

La solution

What have you tried so far?


You need to map elements to frequencies. A mapping generally requires a map, or what's called a dictionary ({} or dict) in Python. So, just count each element in the list (or, in this case, string).

def counter(xs):
    freqs = {}
    for x in xs:
        if x in freqs:
            freqs[x] += 1
        else:
            freqs[x] = 1
    return freqs

Then, e.g., counter("aaaacccbbdd") == {'a': 4, 'c': 3, 'b': 2, 'd': 2}

It's worth noting that you could clean up your existing code considerably.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top