简体   繁体   English

为什么我的 while 循环有时会卡住,但有时不会在我的“秘密圣诞老人”程序中?

[英]Why does my while loop gets stuck sometimes,but sometimes not in my "secret santa" program?

im trying to create basic secret santa function where u can pass list of names to it and it will automaticlly generate random possibilites but while loop sometimes gets stuck and that's the weird part i can not understand why.我正在尝试创建基本的秘密圣诞老人功能,您可以在其中将名称列表传递给它,它会自动生成随机可能性,但有时循环会卡住,这是我无法理解的奇怪部分。

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

So whats happening is sometimes it ends up in the case where one person (for example below person "Y") is the receiver and giver of the gift:因此,有时会发生这样的情况:一个人(例如下面的“Y”人)是礼物的接受者和给予者:

<class 'list'>: ['X', 'W', 'Y', 'Z']
<class 'dict'>: {'X': 'W', 'Z': 'X', 'W': 'Z'}

I ran your code several times in the PyCharm debugger before I got to this case.在遇到这种情况之前,我在 PyCharm 调试器中多次运行了您的代码。 Your while loop condition is:您的 while 循环条件是:

while len(my_dict) != len(listi):

and as you can see this will never be the case as your code is now locked as the if condition person != person2 will never be passed.正如您所看到的,这将永远不会发生,因为您的代码现在被锁定,因为 if 条件person != person2永远不会被传递。

You should take a look at your if condition again and if you cant figure it out mention me in a comment and I'll help you out.您应该再次查看您的 if 条件,如果您无法弄清楚,请在评论中提及我,我会帮助您。 A good idea would be to check what possible combinations are left and if only the condition above is met ie Y is the receiver and giver, discard the list and keep going.一个好主意是检查剩下的可能组合,如果仅满足上述条件,即 Y 是接收者和给予者,则丢弃列表并继续。 This will guarantee you will always exit but is by no means optimal.这将保证您将始终退出,但绝不是最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM