Last active
October 30, 2019 20:52
-
-
Save AO8/1b0e8b35481a9bc761e160156724f017 to your computer and use it in GitHub Desktop.
Create random Secret Santa gift-giving assignments at the click of a button with Python 3.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Step 1: Set up a Google form that collects First Name, Last Name, and Email Address from participants | |
# Step 2: Once all participants have completed the form, export it as a CSV file and store it in the same directory as this program | |
# Step 3: Run the program to create random Secret Santa gift-giving assignments so that each participant is paired with a different participant without duplication or anyone being left out | |
import csv | |
import datetime | |
import random | |
def main(): | |
participants = get_participants_from_csv("test_file.csv") | |
shuffle_participants(participants) | |
pairs = create_pairings(participants) | |
display_pairings(pairs) | |
write_pairings_to_csv(pairs) | |
def get_participants_from_csv(csv_file): | |
"""Extract contents from CSV file and return a participants list""" | |
participants = [] | |
with open(csv_file, "r") as f: | |
reader = csv.DictReader(f) | |
for row in reader: | |
fname, lname, email = row["FirstName"], row["LastName"], row["Email"] | |
participants.append(f"{fname} {lname} ({email})") | |
return participants | |
def shuffle_participants(participants): | |
"""Set random seed to current system time and shuffle list in place""" | |
random.seed(datetime.datetime.now()) | |
return random.shuffle(participants) | |
def create_pairings(participants): | |
"""Iterate over participants list to return a dict of giver, and receiver pairs""" | |
pairs = {} | |
for idx, value in enumerate(participants): | |
pairs[participants[idx]] = participants[(idx+1) % len(participants)] | |
return pairs | |
def display_pairings(pairs): | |
"""Display Secret Santa pairings""" | |
for key, value in pairs.items(): | |
key_name = key.split("(")[0].strip() | |
value_name = value.split("(")[0].strip() | |
print(f"{key_name} is giving a gift to {value_name}.") | |
def write_pairings_to_csv(pairs): | |
"""Write Secret Santa pairings to a new CSV file for reference""" | |
with open("new_pairings_file.csv", "w", newline="") as f: | |
writer = csv.writer(f) | |
writer.writerow(["Giver", "Recipient"]) | |
for key, value in pairs.items(): | |
writer.writerow([key, value]) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment