Assuming that no one gets more than one gift (if they can you might check out itertools.product
). The trick is for every person find any "valid receivers" to apply random.choice()
to. The main criteria seems to be that you can't give to yourself or to the person who gave to you:
I'm sure there are going to be more efficient solutions, but this will get you started:
import random
givers = ['tom', 'dick', 'harry', "joe"]
receivers = givers.copy()
receivers_givers = {}
for giver in givers:
# ---------------------
# You can't give to yourself or to the person who gave to you.
# ---------------------
valid_receivers = [reciever for reciever in receivers if reciever not in (giver, receivers_givers.get(giver))]
# ---------------------
receiver = random.choice(valid_receivers)
receivers.remove(receiver)
receivers_givers[receiver] = giver
for reciever, giver in receivers_givers.items():
print(f"{giver} gifts to {reciever}")
That should give you something like:
tom gifts to joe
dick gifts to harry
harry gifts to tom
joe gifts to dick