Here is a simple Python code snippet that randomly assigns the givers and receivers for a secret Santa gift exchange.
main.py232 chars10 lines
Explanation of the code:
import random: to use the shuffle() method to randomly shuffle the list of namesnames = ["Alice", "Bob", "Charlie", "Dave"]: the list of participants in the gift exchangereceivers = names.copy(): create a copy of the list names for the receiversrandom.shuffle(receivers): shuffle the list of receivers randomlyfor i, name in enumerate(names):: loop through the list of names using enumerate() to get the index and the name at each positionreceiver = receivers[(i+1)%len(names)]: use modular arithmetic to assign the next person in the list of receivers. %len(names) ensures that we wrap around to the beginning of the list.print(name, "gives a gift to", receiver): print the giver and receiver of the gift.Note: This code assumes that there are no duplicates in the list of names. If there are duplicates, you can either remove them before running the code or modify the code to handle duplicates.
gistlibby LogSnag