我正在尝试编写代码为我的表亲选择Secret Santas。到目前为止,我拥有的代码仅适用于偶数用户,但是我有一个奇数或堂兄。
import random
def Santa(names, draw):
matches= []
while names:
giver = names.pop() #chooses giver and removes name
receiver = random.choice(draw) #picks random to receive
if giver != receiver:
matches.append([giver, receiver]) #adds pair
draw.remove(receiver) #removes person from receiving list
else:
names.append(giver) #if names are the same, adds name back to list
return matches
family1=['cousin1', 'cousin2', 'cousin3', 'cousin4']
family2=['cousin5', 'cousin6', 'cousin7','cousin8','cousin9','cousin10']
family3=['cousin11', 'cousin12', 'cousin13','cousin14']
family4=['cousin15', 'cousin16', 'cousin17']
family5=['cousin18', 'cousin19']
names = [ 'cousin1', 'cousin2', 'cousin3', 'cousin4','cousin5']
print(Santa(names,names))
错误为IndexError:无法从空序列中选择 从该行开始:
receiver = random.choice(draw)
我将来会增加的限制之一是您不能拥有兄弟姐妹或姻亲之一。任何有关如何使该功能适用于名字奇数列表或家庭约束的建议都将非常有帮助。
编辑:
如果有人想要做同样的事情,这是我的最终代码。
import random
from copy import copy
def Santa(names, draw):
matches= []
while names:
giver = names.pop()
receiver = random.choice(draw)
if giver[0] != receiver[0]:
if giver[1] != receiver[1]:
matches.append([giver, receiver])
draw.remove(receiver)
else:
names.append(giver)
return matches
family1=['cousin1', 'cousin2', 'cousin3', 'cousin4']
family2=['cousin5', 'cousin6', 'cousin7','cousin8','cousin9','cousin10']
family3=['cousin11', 'cousin12', 'cousin13','cousin14']
family4=['cousin15', 'cousin16', 'cousin17']
family5=['cousin18', 'cousin19']
names = [ ('cousin1', 'parent1'), ('cousin2', 'parent1'), ('cousin3', 'parent1'),('cousin4','parent1'),('cousin5','parent2'),('cousin6','parent2'),('cousin7','parent2'),
('cousin8','parent3'),('cousin9','parent3'),('cousin10','parent3'),('cousin11','parent4'),('cousin12','parent4'),('cousin13','parent4'),('cousin14','parent5'),
('cousin15','parent5'),('cousin16','parent2'),('cousin17','parent2'),('cousin18','parent3'),('cousin19','parent3'),('cousin20','parent2')]
print(Santa(names,copy(names)))
答案 0 :(得分:0)
您的问题是您已将相同的names
数组传递给两个参数。这看起来似乎是正确的,但您必须回想起Python是通过引用传递参数的,因此它们不是两个相同的对象,它们是 same 对象。当您从givers
弹出项目时,它也会从draw
中消失。请尝试以下操作:
import random
from copy import copy
def Santa(names, draw):
matches= []
while names:
giver = names.pop() #chooses giver and removes name
receiver = random.choice(draw) #picks random to receive
if giver != receiver:
matches.append([giver, receiver]) #adds pair
draw.remove(receiver) #removes person from receiving list
else:
names.append(giver) #if names are the same, adds name back to list
return matches
family1=['cousin1', 'cousin2', 'cousin3', 'cousin4']
family2=['cousin5', 'cousin6', 'cousin7','cousin8','cousin9','cousin10']
family3=['cousin11', 'cousin12', 'cousin13','cousin14']
family4=['cousin15', 'cousin16', 'cousin17']
family5=['cousin18', 'cousin19']
names = [ 'cousin1', 'cousin2', 'cousin3', 'cousin4', 'cousin5']
print(Santa(names,copy(names)))
当然,当继续使用两个参数的不同列表时,您实际上并不需要这样做。