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