Sort Characters By Frequency
Question
Write a function to sort the characters in a given string in descending order based on the frequency of occurrence of each character.
Example 1
Input: "tree"
Output: "eert"
Solution
- ▭
- ▯
all//Sort Characters By Frequency.py
def sort_by_frequency(string):
# Make a dictionary of the characters in the string
# and their respective frequencies
char_freq = {}
for char in string:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
# Sort the dictionary in descending order
# based on character frequency
sorted_freq = sorted(char_freq.items(), key=lambda x: x[1], reverse=True)
# Create a new string, with characters sorted by frequency
sorted_string = ""
for item in sorted_freq:
sorted_string += item[0] * item[1]
return sorted_string
# Test
string = "tree"
print(sort_by_frequency(string)) # Output: eert
all//Sort Characters By Frequency.py
def sort_by_frequency(string):
# Make a dictionary of the characters in the string
# and their respective frequencies
char_freq = {}
for char in string:
if char in char_freq:
char_freq[char] += 1
else:
char_freq[char] = 1
# Sort the dictionary in descending order
# based on character frequency
sorted_freq = sorted(char_freq.items(), key=lambda x: x[1], reverse=True)
# Create a new string, with characters sorted by frequency
sorted_string = ""
for item in sorted_freq:
sorted_string += item[0] * item[1]
return sorted_string
# Test
string = "tree"
print(sort_by_frequency(string)) # Output: eert