Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Matrix (whitout numpy) solution in Creative category for Sort Array by Element Frequency by alterGNU
def frequency_sort(items):
# VARIABLES
res = [] # Result List
colonne = len(set(items)) # Matrix length
# EMPTY CASE
if items == []:
return res
# MATRIX
matrice = [ [ None for c in range(colonne) ] for l in range(2) ]
for i in items:
if not(i in matrice[0]): # if new elements, add in matrice
for c in range(colonne):
if matrice[0][c] == None:
matrice[0][c] = i
matrice[1][c] = 1
break
else:
for c in range(colonne): # if elements already in the matrice => incrementation
if matrice[0][c] == i:
matrice[1][c] += 1
# Create Result List Using The MaTriCe
while(max(matrice[1]) != 0):
index = [x for x in range(colonne) if matrice[1][x] == max(matrice[1])]
for op in range(matrice[1][index[0]]):
res.append(matrice[0][index[0]])
matrice[0][index[0]] = None
matrice[1][index[0]] = 0
return res
if __name__ == '__main__':
print("Example:")
print(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4]))
print(frequency_sort([2, 2, 6, 4, 6, 4, 4, 4]))
## These "asserts" are used for self-checking and not for an auto-testing
assert list(frequency_sort([4, 6, 2, 2, 6, 4, 4, 4])) == [4, 4, 4, 4, 6, 6, 2, 2]
assert list(frequency_sort(['bob', 'bob', 'carl', 'alex', 'bob'])) == ['bob', 'bob', 'bob', 'carl', 'alex']
assert list(frequency_sort([17, 99, 42])) == [17, 99, 42]
assert list(frequency_sort([])) == []
assert list(frequency_sort([1])) == [1]
print("Coding complete? Click 'Check' to earn cool rewards!")
May 14, 2021