Sales by Match : HackerRank Solution in Python

Shounak Lohokare
2 min readJan 2, 2021

Solution in Python 3

def sockMerchant(n, ar):
countOfSocks = []
for sock in set(ar):
countOfSocks.append(ar.count(sock))
return sum([i//2 for i in countOfSocks])

Explanation

First, we will declare an empty list, countOfSocks. In which we will store the count of each type of sock.

countOfSocks = []

Then, we will iterate over the set of ar through a variable sock. The set() function in Python is a data type which does not have duplicate elements. Hence it will just contain just the types of socks.

for sock in set(ar):

Inside the for loop we will append the count of each sock in ar to the list countOfSocks.

We use the count function which returns an integer of occurrences of an element in a list. In the above for loop, The above count function returns the occurrences of sock in ar.

At the end we will return the sum of a list comprehension,

return sum([i//2 for i in countOfSocks])

The list comprehension will form a list having number of pairs of each type of sock in the countOfSocks as elements. The list comprehension will perform floor division operation of 2 (i//2) on each element of countOfSocks, For example, If an element of countOfSocks is 11, the floor division operator will result to 5 because if there are 11 single socks it results to 5 pairs of socks.

We use the sum function, which sums all number elements in the list, on the above list comprehension which will result to total number of pairs of socks that can be formed from a list ar.

--

--

Shounak Lohokare

pretending to teach is one of the best way to learn.