'How should I fix my code for Sock Merchant with runtime error
Though I wrote a code for Sock Merchant on HackerRank, I've stacked on one error.
I tried to visualize the transition of the array named ar, but I have not found the reason why the error list index out of range is caused yet.
Code:
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
num = 0
for i in range(len(ar)):
if ar.count(ar[i]) > 1:
if ar.count(ar[i]) % 2 == 0:
num += ar.count(ar[i]) // 2
print(num) #2
print(ar[i])
while ar[i] in ar:
ar.remove(ar[i])
#[20, 20, 30, 50, 20]
else:
num += math.ceil(ar.count(ar[i]) // 2)
print(num) #3
while ar[i] in ar:
ar.remove(ar[i])
#[30, 50]
else:
continue
return num #3
if __name__ == '__main__':
n = 9
ar =[10, 20, 20, 10, 10, 30, 50, 10, 20]
result = sockMerchant(n, ar)
print(result)
Output:
Finished in N/A
2
10
IndexError: list index out of range
Line 18 in sockMerchant (Solution.py)
Line 36 in <module> (Solution.py)
Solution 1:[1]
static int sockMerchant(int n, int ar[]) {
int num_pairs = 0;
if (ar.length == 0) {
return num_pairs;
}
Set < Integer > set = new HashSet();
for (int i = 0; i < ar.length; i++) {
if (!set.contains(ar[i])) {
set.add(ar[i]);
} else {
num_pairs++;
set.remove(ar[i]);
}
}
return num_pairs;
}
Solution 2:[2]
Trying another approach in Python for the "Sock Merchant" challenge.
In here I used the Counter function by importing from the "collections" Library.
After arranging it into Dictionary values I counted the number of pairs which are more than one by truncating it... that is n//2.
from collections import Counter
#You can use this list #
#or possibly any other ones.
my_lst = [50, 20, 30, 90, 30, 20, 50, 20, 90]
def sock_merchant(my_lst):
a = dict(Counter(my_lst))
print(a)
pairs = []
for value in a.values():
if value > 1:
pairs.append(value//2)
return sum(pairs)
sock_merchant(my_lst)
Solution 3:[3]
def sockMerchant(n, ar):
s=0
for val in Counter(ar).values():
s+=val//2
return s
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | phwt |
| Solution 2 | BTables |
| Solution 3 | Hansen Marcelino Azali |
