Last active
December 11, 2016 21:05
-
-
Save gsong/a970a1843b5f7f5e661bc6b901ecdbcd to your computer and use it in GitHub Desktop.
Christmas gift exchange
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from random import sample | |
# people grouped together cannot gift to each other | |
people = [ | |
('Sue', 'Sam'), | |
('Heather', 'Matt'), | |
('Noelle', 'George'), | |
] | |
gifters = set([p for group in people for p in group]) | |
def my_group(person): | |
for group in people: | |
if person in group: | |
return group | |
def gifter_for(person, pairs): | |
for k, v in pairs.items(): | |
if v == person: | |
return k | |
return None | |
def remaining_recipients(gifter, gifters, pairs): | |
group = my_group(gifter) | |
possible_recipients = gifters - set(group) - set(pairs.values()) | |
giver = gifter_for(gifter, pairs) | |
if giver: | |
possible_recipients -= {giver} | |
return possible_recipients | |
def pair_up(gifters): | |
pairs = {} | |
for gifter in gifters: | |
possible_recipients = remaining_recipients(gifter, gifters, pairs) | |
try: | |
recipient = sample(possible_recipients, 1)[0] | |
except ValueError: | |
pairs = {} | |
break | |
pairs[gifter] = recipient | |
if pairs: | |
return pairs | |
else: | |
print('Try again...') | |
pairs = pair_up(gifters) | |
return pairs | |
def main(): | |
pairs = pair_up(gifters) | |
for k, v in pairs.items(): | |
print("{} → {}".format(k, v)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment