I want to solve this problem:
Given an input string, sort the characters in decreasing order of frequency. If more than one characters had same frequency count, sort them in increasing lexicographical order. Example:
bdca --> abcd,
bdcda -> ddabc,
abba -> aabb,
bacbdc -> bbccad,
My solution involves creating the frequencies in a hash map, sorting the hash map dict items by frequency using sorted() and lambda function. Then for the items with the same frequency (I need to write a subroutine for this), I do another sorted with lambda function.
def string_sort(s):
hmap = {}
for char in s:
if char not in hmap:
hmap[char] = 1
else:
hmap[char] += 1
freqs = sorted(hmap.items(), key=lambda x: x[1], reverse=True)
num_occur: list = find_num_occur(freqs)
sorted_freqs = []
start_ind = 0
for f in num_occur:
tmp_freqs = sorted(freqs[start_ind : start_ind + f], key=lambda x: x[0])
sorted_freqs.extend(tmp_freqs)
start_ind = len(sorted_freqs)
out = []
for item in sorted_freqs:
out.extend([item[0]] * item[1])
return "".join(out)
def find_num_occur(freqs):
count = 1
out = []
for i in range(len(freqs) - 1):
if freqs[i][1] == freqs[i + 1][1]:
count += 1
else:
out.append(count)
count = 1
out.append(count)
return out
The solution is not elegant. I was told I can solve it easier if using comparators, but I don't know how to use comparators in python. Any suggestions? Or any other more elegant solution?
Thanks.