We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
The big takeaway I got from this problem is that whenever you're asked to sort according to multiple criterias, sorting in reverse order of the criterias does the trick.
For instance, we were asked to sort according to frequencies, then to sort any two characters that have the same frequencies alphabetically.
To achieve this, we simply sort alphabetically first, then sort according to frequency.
Took me a while to realize this :)
My solution:
s=input()# create dictionary of each character and their frequencyfrequencies={}forcharins:ifcharinfrequencies:frequencies[char]+=1else:frequencies[char]=1# convert dictionary into more sortable formatfrequencies=list(frequencies.items())# sort by characters alphabeticallyfrequencies=sorted(frequencies,key=lambdaitem:item[0])# sort by frequencies in descending orderfrequencies=sorted(frequencies,key=lambdaitem:item[1],reverse=True)# print the first 3 items ()forchar,frequencyinfrequencies[:3]:print(char,frequency)
Company Logo
You are viewing a single comment's thread. Return to all comments →
The big takeaway I got from this problem is that whenever you're asked to sort according to multiple criterias, sorting in reverse order of the criterias does the trick. For instance, we were asked to sort according to frequencies, then to sort any two characters that have the same frequencies alphabetically. To achieve this, we simply sort alphabetically first, then sort according to frequency. Took me a while to realize this :)
My solution: