i am a newbie to Python and i am trying to learn through sites like HackerRank.
Can someone please explain how to do this?
Given an array of integers, create a 2-dimensional array where the first element is a distinct value from the array and the second element is that value’s frequency within the array. Sort the resulting array descending by frequency. If multiple values have the same frequency, they should be sorted ascending.
This is the portion of code provided
import math
import os
import random
import re
import sys
#
# Complete the 'groupSort' function below.
#
# The function is expected to return a 2D_INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def groupSort(arr):
# Write your code here
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr_count = int(input().strip())
arr = []
for _ in range(arr_count):
arr_item = int(input().strip())
arr.append(arr_item)
result = groupSort(arr)
fptr.write('\n'.join([' '.join(map(str, x)) for x in result]))
fptr.write('\n')
fptr.close()
>Solution :
First of all, you need to figure out the frequency of each of the numbers in the array.
To do this you can use a dictionary. Create a dictionary, and then iterate through all the numbers. For each number check if you already have that number in the dictionary. If you have, then increment its value by one. Otherwise create a new key in the dictionary, with the value of 1.
Here is the code for that:
d = {}
for n in arr:
if n in d:
d[n] += 1
else:
d[n] = 1
Now you need to sort the values based on the frequency in descending order. To do this you can use in-built sort method of python list. First, create a list that contains both the number and its frequency.
Here is the code for that:
res = [[k,v] for (k,v) in d.items() ]
Now you can sort it. Since you want it in descending order, you need to reverse the sorting order by passing reverse = True parameter to the sort function. Also, Since you need to sort based on the frequency of the number, which is the second value in each of the listitem in the list, you need to pass a key parameter with a lambda function to specify that.
Here is the code for that:
res.sort(key=lambda x: x[1], reverse=True)
At the end you just need to return the result.
return res
Here is the full code:
def groupSort(arr):
d = {}
for n in arr:
if n in d:
d[n] += 1
else:
d[n] = 1
res = [[k,v] for (k,v) in d.items() ]
res.sort(key=lambda x: x[1], reverse=True)
return res
print(groupSort([1,2,3,3,4,5,9,2,5,5,6,8]))