Last active
December 21, 2021 23:54
-
-
Save les-peters/b1d49f95d2d21fec5b1893892ac3d97a to your computer and use it in GitHub Desktop.
White Elephant
This file contains hidden or 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
| question = """ | |
| Design a data structure and functions for a white elephant game. | |
| You'll want to have a set of players and gifts they bring, and | |
| the gifts they end up with in the end! | |
| """ | |
| import random | |
| from pprint import pprint | |
| def take_gift(attendee, gift): | |
| if gifts[gift]['held_by'] is None: | |
| gifts[gift]['held_by'] = attendee | |
| attendees[attendee]['gift_holding'] = gift | |
| else: | |
| was_holding = gifts[gift]['held_by'] | |
| attendees[was_holding]['gift_holding'] = None | |
| gifts[gift]['held_by'] = attendee | |
| gifts[gift]['stolen'] = True | |
| attendees[attendee]['gift_holding'] = gift | |
| random_gift = select_gift(was_holding) | |
| if random_gift: | |
| take_gift(was_holding, random_gift) | |
| return | |
| def join_party(name, gift): | |
| attendee_record = { 'name': name, 'gift_brought': gift, 'gift_holding': None } | |
| attendees[name] = attendee_record | |
| gift_record = { 'name': gift, 'from': name, 'stolen': False, 'held_by': None } | |
| gifts[gift] = gift_record | |
| return | |
| # your available gifts cannot be previously stolen, and cannot be brought by you | |
| def select_gift(attendee): | |
| available_gifts = [] | |
| for gift in gifts.keys(): | |
| if gifts[gift]['from'] != attendee and gifts[gift]['stolen'] is False: | |
| available_gifts.append(gifts[gift]['name']) | |
| if len(available_gifts) == 0: | |
| return None | |
| else: | |
| random_gift_id = int(random.random() * len(available_gifts)) | |
| random_gift = available_gifts[random_gift_id] | |
| return random_gift | |
| gifts = {} | |
| attendees = {} | |
| join_party('Alice', 'apples') | |
| join_party('Betty', 'bananas') | |
| join_party('Chloe', 'carrots') | |
| join_party('Doris', 'dates') | |
| join_party('Ellen', 'eggs') | |
| join_party('Frank', 'fudge') | |
| join_party('Gregg', 'grapes') | |
| join_party('Harry', 'hamburgers') | |
| join_party('Issac', 'ice cream') | |
| join_party('James', 'jelly') | |
| first = True | |
| final_attendee = None | |
| for attendee in attendees.keys(): | |
| if first is True: | |
| final_attendee = attendee | |
| first = False | |
| random_gift = select_gift(attendee) | |
| if random_gift: | |
| take_gift(attendee, random_gift) | |
| random_gift = select_gift(final_attendee) | |
| if random_gift: | |
| take_gift(final_attendee, random_gift) | |
| pprint(gifts) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment