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â€¦