Given a string, you have to find the first n
most frequent characters in it.
If there are two letters with the same frequency, then the alphabetically earlier value should be picked first:
string= "aabbccc"
n =2
list = []
#write your code here
char_dict = {}
for char in string:
if char not in char_dict:
char_dict[char] = 1
else:
char_dict[char] += 1
sorted_dict=sorted(char_dict.items(), key=lambda x: (x[1],x[0]))
sorted_dict = sorted_dict[-2:]
for key, value in sorted_dict:
list.append(key)
print(list)
My output is ['b', 'c'] but it should actually be c and a.