Let's practice with a basic Secret Santa generator in Python.
What is Secret Santa?
Secret Santa is a very popular Christmas tradition. The idea is to exchange very cheap but funny gifts with your colleagues or your friends.
There are three mandatory rules:
- each member is assigned to another member randomly
- each member will buy a gift and receive one
- a member cannot select his own name
Avoid common misconceptions
You don't need an even number of participants to organize a Secret Santa.
You might get confused, as the whole operation consists of making pairs, but the size of the stack does not matter here :)
Map the problem
Let's say there are seven members for the Secret Santa Event: A, B, C, D, E, F, and G.
The trivial example would be:
A->B->C->D->E->F->G->A
Looks easy! We can probably assign pairs according to an ordered list of elements to make pairs in the same order.
However, anyone could easily guess all pairs, ruining the whole experience. Let's shuffle!
Basic Python program
Warning: we must implement the mandatory rules.
It's possible, at least, in four steps:
- take the names as inputs
- store the names in a list
- shuffle the list
- assign unique pairs
We will process a .csv
file that contains two different lists of members:
John,Sarah,Paul,Jenny,Oliver,Maria,Elliot
Joyce,Helena,Ella,Robert,Marla,Eva,Kate
Python will abstract the complexity. The built-in enumerate()
will keep a count of iterations so we'll know when to stop:
#!/usr/bin/env python3
import sys
import random
import csv
"""Generate secret santa pairs from a list of members
"""
def make_secret_santa_pairs(members):
total = len(members)
random.shuffle(members)
pairs = [
(member, members[(j + 1) % total])
for j, member in enumerate(members)
]
print("[+]", pairs)
try:
with open("members.csv", mode="r") as csv_file:
csv_items = csv.reader(csv_file)
for item in csv_items:
if len(item) > 0:
make_secret_santa_pairs(item)
except Exception as e:
print("[-] Error while setting members with the .csv file:", e)
sys.exit(1)
N.B.: I use a .csv here because I'm lazy, but feel free to replace it with a prompt or something more interactive
What to do after
- send invitations to each member by email
- provide user accounts
- add wish lists
- add an interface to enter names instead of using .csv files
And many more... In this post, we barely scratched the surface.
Wrap this up
Such loops and permutations are not uncommon in programming, so it can be nice to practice with a concrete case.