# Got a bit of a Sock problem here!

Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.

sockMerchant has the following parameter(s):

• n : the number of socks in the pile
• ar : the colors of each sock

Input Format

The first line contains an integer n, the number of socks represented in ar.
The second line contains n space-separated integers describing the colors ar[i] of the socks in the pile.

My Code:

``````import math
import os
import random
import re
import sys

def sockpair(n,ar):
ar.sort()
print(ar)
pair=0
for i in range(n+1):
try:
if ar[i]==ar[i+1]:
ar.pop(i)
ar.pop(i+1)
pair+=1

except:
pass

for j in range(n+1):
try:
if ar[j]==ar[j+1]:
ar.pop(j)
ar.pop(j+1)
pair+=1

except:
pass

return pair
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

n = int(input())

ar = list(map(int, input().rstrip().split()))

result = sockpair(n, ar)

fptr.write(str(result) + '\n')

fptr.close()
``````

My logic is like I want to run a loop and if I find a pair of sock in the list I want to pop it out of the list and make a count of pair I can make from the sock list, but now I am stuck for like 3 hours and don’t know what to do…somethings wrong with my sockpair() function…

Why not submit your code to hackerrank.com so you can see what others are trying, or are you worried this will impact your ranking / leaderboard position?

Yep! I already submitted my code and it has way too many faults, not worried about the rank or leader board, actually I can easily get the solution out from discussion on hacker-rank but I am trying to implement the logic which I thought first that it might work…

I’d have to see this data (which weirdly looks like a C program translated into a Python challenge), but usually you’d want to use a dict for this. A dict looks like this:

sock_pairs = {}

A “dict” is a dictionary, so it maps from one thing to other things, just like words in a dictionary. My rough guess it that you want to do something like:

sock_pairs[n] += 1

But you’ll have to do some juggling to make sure that it’s in there first. Try it out with dicts and see if that works better.

1 Like