Here’s my code for taking an example string and creating a list of tuples of the alphanumeric characters in the string along with their frequencies of occurrence. Sorting the list of tuples according to the frequencies of occurrence is easy. The more difficult task for me was sorting the characters from earliest occurring in the alphabet to latest, BUT keeping the order of frequencies and only sorting within characters of the same frequency. The way I did this was by creating a new, empty list, then for each occurrence frequency creating a new sorted list according to the earliest to latest letter, and finally adding each sorted list in turn to the newly created list. Is there a simpler, more elegant way of accomplishing this result? (I feel like there should be, but I can’t think of it.)
My code:
from pprint import pprint
phrase = “This is a common interview question. To be or not to be, that is the question.”
char_frequency = dict()
for char in phrase.lower():
if char.isalpha():
char_frequency.setdefault(char, 0)
char_frequency[char] += 1
max_frequency = max(char_frequency.values())
char_frequency_sorted = sorted(char_frequency.items(),
key=lambda kv:kv[1],
reverse=True)
pprint(char_frequency_sorted, width=12)
print()
for char, count in char_frequency_sorted:
if count != max_frequency:
break
else:
print(f"Maximum Occurring Character: {char}, Count = {count}")
print()
counts = list(set(char_frequency.values()))
counts.sort(reverse=True)
updated_sort =
for count in counts:
filtered_count_list = list(filter(lambda item: item[1] == count, char_frequency_sorted))
updated_sort += sorted(filtered_count_list, key=lambda item:item[0])
pprint(updated_sort, width=12)