I want to implement this without using the sorted function (perhaps by using a priority queue):
nums = [2,3,1,3,2]
dic=collections.Counter(nums)
sorted_dic= dict(sorted(dic.items(),key=lambda x: x[1]))
I have written a custom sort function to sort array/dictionary in ascending/descending order.
def bubble_sort(arr): #You can use any sort - for the sake of simplicity I have used bubble sort
for i in range(len(arr)-1):
for j in range(len(arr)-1-i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def my_custom_sort(obj,key=None,reverse=False):
if type(obj)==dict:
if key==0:
arr = list(map(lambda x:x[0], obj.items())) #fetch the list of keys
else:
dic = {y:x for x,y in obj.items()} #reverse the key value pairs, so that it is easy to match key/values
arr = list(map(lambda x:x[0], dic.items()))
else:
arr=obj
sorted_arr = bubble_sort(arr)
if reverse: sorted_arr =sorted_arr[::-1]
if type(obj)==dict:
if key==0:
res = [(key,obj[key]) for key in sorted_arr]
return res
else:
return [(dic[key],key) for key in sorted_arr]
return res
else:
return sorted_arr
arr=[4,2,6,7,1]
dic={3:1,2:4,1:0,0:8}
print(my_custom_sort(arr)) #sort array in increasing order
print(my_custom_sort(arr,reverse=True)) #sort array in decreasing order
print(my_custom_sort(dic,key=0)) #sort dictionary by key in inreasing order
print(my_custom_sort(dic,key=1)) #sort dictionary by values in increasing order
print(my_custom_sort(dic,key=0,reverse=True)) #sort dictionary by key in decreasing order
print(my_custom_sort(dic,key=1,reverse=True)) #sort dictionary by values in decreasing order
Output:
[1, 2, 4, 6, 7]
[7, 6, 4, 2, 1]
[(0, 8), (1, 0), (2, 4), (3, 1)]
[(1, 0), (3, 1), (2, 4), (0, 8)]
[(3, 1), (2, 4), (1, 0), (0, 8)]
[(0, 8), (2, 4), (3, 1), (1, 0)]
I hope this is helpful for someone who wants to implement his own custom sort function (if asked in the interview)