My Matching Socks Quest

Hey all. So I’m creating my first Python app that matches socks. My first attempt was not very efficient. The code included an integer set that I converted to a list and then, finally, converted to a dictionary. The code ended up being roughly 40 lines and was ridiculously complicated. I created a dictionary with a key of the number of socks and a value of the color sock. After doing this, I used the ‘sorted’ method, which was a major problem. If there were an equal number of socks, the function simply excluded that sock. This really confused me at first since I would input 20 socks and receive an output of 15 or so colors. Anyway, I simplified the code into: an input, a single function, use of the ‘random’ library, a while statement (with an accelerator), a set of if-elif-else statements, and one list using the .sort() method. This literally cut my code in half and is far more efficient. After some thought, I did change everything around a bit. My previous code allowed me to sort the socks, but not match them. Ultimately, the ability to do both is important. I did come up with another option using list comprehension with random.choice. The problem with this is that I am able to patch different colors, but there is no sorting involved. So this could have obviously poor implications for real life application. My most accurate function does allow for both matching and sorting. This involves adding a certain number of socks to a default list, then popping socks off the list in multiples of 2 and adding it to a new list. The big problem with this is that creating each list is manual. So I would need to create a new list for every 2 new socks created. The upside is that I’m getting closer to a solution. Here’s my next update. I did it! I figured out an algorithm that both sorts and matches. I basically combined my code from my previous inefficient sort/match code with the much more efficient match code. I’ve included an input for number of socks, then random.choice(colors). I use a while state with an aggregator, then I use a .sort() statement. Then I use another while statement to pop 2 values at a time and append both to a second list. This both sorts and matches. The only downside now is that, at times, there will be two socks of the same color that are matched up to different colors due to their location in the original list. I will see whether or not I could solve this problem. The code is concise at just 16 lines and actually works much better than anything I’ve found on Stack Exchange. Very exciting! I think I’m getting this!

This is a Sidebar

I might put something here eventually.

  • Latest Posts
  • Announcements
  • Calendars
  • etc