Sales by Match : HackerRank Solution in Python

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.

--

--

--

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

Centralized Config Service in Spring Boot

Meet CoinBundle’s Programmers

Summarizing “RethinkDB: why we failed”

My 10 Principles to follow as a Developer

Importance of commenting on your Python’s program — Beginner’s Guide

Develop Software in Team with Git and Gitlab

Date command in Linux

Hey, wouldn’t it be cool to have…

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

List comprehension in Python

Pandas Tutorial Part V — Analyzing and Exploring Data

Python: Variables and Assignments

Photo by Brookside Admin

String in Python