I am trying to write an algorithm to rearrange the letters in a string in order of frequency and then alphabetical order. For instance, “apple” becomes “aelpp”. “banana” becomes “bnnaaa”.
I know a variety of languages, but I am using Python for now to code it. This is what I have so far, but it does not work because there is no frequency sorting.
def order(word):
word = word.lower()
storage = [0] * 26
for c in word:
storage[ord(c) - 97] += 1
newWord = []
for l, c in enumerate(storage):
for i in range(0, storage[l]):
newWord.append(chr(l + 97))
return ''.join(newWord)
Any advice on how to most efficiently implement this algorithm correctly?
Here is a (mostly) pythonic example of how to deal with this problem in python,
I hope the comments are sufficient to explain what is happening:
this implementation will keep capital letters capital.