Skip to content

Instantly share code, notes, and snippets.

@rmasters
Created November 20, 2010 17:27
Show Gist options
  • Save rmasters/707985 to your computer and use it in GitHub Desktop.
Save rmasters/707985 to your computer and use it in GitHub Desktop.
Generate single-direction pairs of people for secret santa (i.e. A sends to B, but not B sends to A).
"""
Secret santa matching attempt
"""
import random
"""
Match people randomly to others, for example in a secret santa
Takes a list of people as an input and returns a list of tuples (person a sending to person b)
"""
def secret_santa(people):
# This list holds the positions in the people list of people who haven't been matched
people_indexes = range(0, len(people))
# Our matches list
matches = []
if len(people_indexes) < 2:
raise Exception("You can't have a secret santa with one person!")
# and it won't be a very good one with two people either ;)
# Let's pair people up!
current = 0
while len(people_indexes) > 0:
# The position of the current unmatched person in people
current_index = people_indexes[current]
# If we're on our last person join them up with the first person
if len(people_indexes) == 1:
matches.append((people[current_index], matches[0][0]))
break
# Get the next person - remove the current person's position and select a random position
people_indexes.pop(current)
next = random.randrange(0, len(people_indexes))
# The position of the next unmatched person in people
next_index = people_indexes[next]
# Add the match to our matches list and set current to be the next person
matches.append((people[current_index], people[next_index]))
current = next
return matches
print secret_santa(["Ross", "Paul", "Rich", "Santa", "Elf", "David Attenborough", "The Lich King"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment