I am trying to write a Secret Santa type of program. The function takes in a list of names as a parameter and is supposed to match each person with another person. No one can be matched with themselves, and each person can only receive and give one gift. It is a simple program so I’ll include the entire thing.
import random
Game1 = ["Alice", "Bob", "Charlie", "David", "Eve", "Frank"]
def matchPeople(players):
needGift = players
matches = []
for player in players:
def getReceiver():
receiver = random.choice(needGift)
if receiver == player:
getReceiver()
else:
matches.append([player, receiver])
needGift.remove(receiver)
getReceiver()
print(matches)
matchPeople(Game1)
It is running as expected (I think), except it is stopping after 3 iterations. Upon running the matchPeople() function this is the outcome. I am very new to python (coming from JS), so I’m sure there is a logical explanation. However! I do not know what it is…
[['Alice', 'Charlie'],
['Bob', 'David'],
['Eve', 'Bob']]
>Solution :
Your problem here is that needGift and players refer to the same object in memory – and when you remove elements from it inside your nested function, they are also removed from the player list.
The change listed bellow will make needGift a copy of the players list (by taking a "slice" starting at the begging and proceeding to the end of it – the default slice values when you suppress the indexes around the :)
change
needGift = players
to
needGift = players[:]