Question: In Python: 1. Add to the starter code above to make sure that 1) nobody is assigned to buy a gift for themselves, and 2)

In Python:

1. Add to the starter code above to make sure that 1) nobody is assigned to buy a gift for themselves, and 2) each person can only give one gift and can only receive one gift (no repeats). Have the program keep trying (looping) until both of these conditions are met. The program should work every time regardless of the number of people participating.

2. How can we avoid a closed loop where, for example, Player #1 buys a gift for Player #4, and vice versa effectively closing them off from everyone else?

3. Assuming that your solution was to completely restart from scratch and reassign everybody if even one person was assigned to give a gift to themselves - which is inefficient - can you design a better, more efficient algorithm? (HINT Its ok to create new lists!)

4. Sometimes, it's no fun for certain people in a big gift exchange to buy gifts for each other (like spouses who will probably buy gifts for each other anyway). Can you edit this p

Code:

# Gift-assigner program

import random

numPeople = int(intput("How many people are playing? "))

givers = []

recivers = []

print("Please enter their names: ")

# Get all of the players' names and add them to the list

for i in range(numPeople):

givers.append(input(""))

# Randomly assign gift givers to gift receivers. Check to make sure that nobody is assigned themselves (which is no fun!), and that each person can only give one gift and can only receive one gift (no repeats). Keep trying (looping) until everyone is giving a gift to someone else.

for j in range(numPeople):

recivers[j] = random.sample(givers, numPeople)

# Print results

print()

print("Gift Assignments...")

for k in range (numPeople):

print(givers[k], "will buy a gift for," recivers[k])

print()

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!