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
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}")