![](/img/trans.png)
[英]Why does this regular expression sometimes get stuck and freeze my program? what alternative could i use?
[英]Why does my while loop gets stuck sometimes,but sometimes not in my "secret santa" program?
我正在尝试创建基本的秘密圣诞老人功能,您可以在其中将名称列表传递给它,它会自动生成随机可能性,但有时循环会卡住,这是我无法理解的奇怪部分。
def santa(listi):
from random import shuffle,choice
my_dict = {}
shuffle(listi)
while len(my_dict) != len(listi):
person = choice(listi)
person2= choice(listi)
if person!= person2 and person2 not in my_dict.values() and person not in my_dict.keys():
my_dict.update({person:person2})
else:
continue
return my_dict
因此,有时会发生这样的情况:一个人(例如下面的“Y”人)是礼物的接受者和给予者:
<class 'list'>: ['X', 'W', 'Y', 'Z']
<class 'dict'>: {'X': 'W', 'Z': 'X', 'W': 'Z'}
在遇到这种情况之前,我在 PyCharm 调试器中多次运行了您的代码。 您的 while 循环条件是:
while len(my_dict) != len(listi):
正如您所看到的,这将永远不会发生,因为您的代码现在被锁定,因为 if 条件person != person2
永远不会被传递。
您应该再次查看您的 if 条件,如果您无法弄清楚,请在评论中提及我,我会帮助您。 一个好主意是检查剩下的可能组合,如果仅满足上述条件,即 Y 是接收者和给予者,则丢弃列表并继续。 这将保证您将始终退出,但绝不是最佳选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.