5 comments

[ 4.8 ms ] story [ 25.9 ms ] thread
This year my friend group is using Elfster to distribute secret santa names. This got me thinking about how to write a good implementation of the secret santa "elf". The problem has some interesting properties: a good algorithm should never assign a person to give a gift to him/herself. I extended that property to say that no pair of people should send/rec'v from each other. Extending this out, we might even say a good secret santa will ensure there are no partitions in the group: following the linked list of senders, you should iterate over everyone in the group.

Viewed like that, an "optimal" solution is brilliantly simple: given n names, shuffle the array of names, then assign person[k] to give to person[k+1], with the special case where k == n, person[k] gives to person[0].

The rest of the short implementation adds a `receive_from` property to each person which could be useful in QAing the implementation.

If you still need to assign Secret Santa givers, feel free to use my implementation!

My implementation:

  def santa_list(people):
      return dict(zip(
                  people[1:] + people[:1],
                  people))
(shuffle if you want to).
That's brilliantly simple. I really need to use `zip` more often in my python code. Thanks for sharing your succinct solution.
Awesome script! Will give it a try next year.