Sales by Match : HackerRank Solution in Python

Solution in Python 3

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


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.




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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The wisdom of making code changes

GraphQL API Server using Spring Boot & Spring Data JPA: A How-to Guide

Embedded GraphiQL tool

Spring Batch — Pass Data from One step to another

DIY Password Manager using Azure Key Vault because .. why not?

How to use Terraform and Ansible to raise a Jenkins Server on DigitalOcean

Implementing and Explain High Availability with HSRP

The 7 tools I can’t live without

Cdj 2000 Traktor Scratch Pro 2

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Shounak Lohokare

Shounak Lohokare

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

More from Medium

Lambda Functions in Python -II

Python queries to work with multiple instances of Oracle and SQL Server.

Python Algorithm Pt.8: heap tree

A magical day in Disney with Machine Learning — Part 3 Getting used to data