Skip to content

Commit a34b73a

Browse files
Merge pull request #1093 from aldomelpignano/main
Merged - Code reviewed and approved
2 parents 01ce7a0 + eb1acdd commit a34b73a

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
def sort_by_frequency(arr):
2+
"""
3+
Sort the elements of a list based on their frequency in descending order.
4+
If two elements have the same frequency, they are sorted in ascending order.
5+
"""
6+
if not arr:
7+
return []
8+
9+
# Count the frequency of each number manually
10+
frequency = {}
11+
for num in arr:
12+
if num in frequency:
13+
frequency[num] += 1
14+
else:
15+
frequency[num] = 1
16+
17+
# Create a copy of the array to sort
18+
result = arr[:]
19+
20+
# Sort by descending frequency, then by ascending value
21+
result.sort(key=lambda x: (-frequency[x], x))
22+
23+
return result
24+
25+
26+
if __name__ == "__main__":
27+
example = [4, 5, 6, 4, 5, 4]
28+
result = sort_by_frequency(example)
29+
print("Input:", example)
30+
print("Output:", result)

0 commit comments

Comments
 (0)