Python coding challenge - Sorting socks solution analysis
2 min read

Python coding challenge - Sorting socks solution analysis

Question Posted in a facebook group https://www.facebook.com/groups/python/permalink/1163918304448732/
After doing your laundry, you now have a bag full of socks to pair up and sort. right and left socks are mirror images of each other so 'ad' is paired with 'da', 'p1' with '1p' etc. write code to pair and sort your socks, putting leftover singles in a separate 'bag' for next time.

socks = ['lv,eb,ho,ug,da,be,se,kc,p1,ck,gu,vl,nb,ad']
your output should be
pairs = [['ad','da'],['be','eb'],['ck','kc'],['gu','ug'],['lv','vl']]
singles = ['nb','p1','ho','se']

A function to generate a random 2 char string

#random 2 digit char ex. 'ab', 'cd', 'ef'
import random
def rand_char():
    a = chr(random.randint(97,122)) 
    b = chr(random.randint(97,122))
    #don't return same char twice ex. 'aa', 'bb', 'cc'
    if a == b:
        return rand_char()
    else:
        return a+b
dummy_data = [rand_char() for i in range(100000)]

Different Solutions Different Runtime

Solution by Carl F. Corneil - 17.4s
Solution by Vishal Basumatary - 0.6s
Solution by Robert Nix - 18.8s
Solution by Francesco Loffredo - 0.2s
Takes more than a minute. Stopped execution

Full Solution

#Full solution for the test
socks = ['lv,eb,ho,ug,da,be,se,kc,p1,ck,gu,vl,nb,ad']
socks = socks[0].split(",")
seen = set()
pairs = []
for sock in sorted(socks):
  reverse = sock[::-1]
  if reverse in seen:
    pairs.append([reverse, sock])
    seen.remove(reverse)
  else:
    seen.add(sock)
print(f"pairs = {pairs}\nsingles = {sorted(seen)}")

Counter based solution to support duplicate pairs

#Full solution for the test
from collections import Counter
socks = ['lv,eb,ho,ug,da,be,se,kc,p1,ck,gu,vl,nb,ad']
socks = socks[0].split(",")
seen = Counter()
pairs = []
for sock in sorted(socks):
  reverse = sock[::-1]
  if seen[reverse]:
    pairs.append([reverse, sock])
    seen[reverse] -= 1
  else:
    seen[sock] += 1
singles = []
for char, count in sorted(seen.items()):
  for i in range(count):
    singles.append(char)
print(f"pairs = {pairs}\nsingles = {singles}")

Enjoying these posts? Subscribe for more


Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×