在Python中循环这个错误是什么?

时间:2017-12-13 22:45:46

标签: python python-3.x math

好的,所以我花了好几个小时试图解决这个问题,我觉得它有一些简单的错误,但我找不到办法解决这个问题。 我遇到问题的部分是代码的后半部分。在2个嵌套的while循环中似乎存在无限循环。如果有人能够提供帮助,这将是非常好的,感谢提前。

import sympy as sym
import random

A, B, C, D, E, F, G, H, I, J = sym.symbols('A, B, C, D, E, F, G, H, I, J')
picks_a_person = [A, B, C, D, E, F, G, H, I, J] #List of people picking a name from a hat
person_gets_picked = [A, B, C, D, E, F, G, H, I, J] # List of names drawn from a hat
def re_draws(p):
    n = 0
    count = 0
    while n < 1000: #Repeats the test 1000 times for an accurate percentage
        n += 1
        random.shuffle(person_gets_picked) #Chooses a random order of the list of names drawn
        for i in range(p):
            if person_gets_picked[i] == picks_a_person[i]: #Checks for all 'p' elements of the lists are different
                count = count + 1
    print("count = " + str(count)) #Returns the number of times a re-draw was not required

import numpy as np
from collections import Counter

total = []
while len(total) < 1000:
    order = []
    picks_a_person = [A, B, C, D, E, F, G, H, I, J]
    person_gets_picked = [A, B, C, D, E, F, G, H, I, J]
    while len(order) < 10:
        a = person_gets_picked[random.randint(0, (len(person_gets_picked)-1))]
        if a != picks_a_person[0]:
            order.append(a)
            person_gets_picked.remove(a)
            del picks_a_person[0]
    total.append(order)
Counter(np.array(total)[:,1])

1 个答案:

答案 0 :(得分:2)

虽然你的代码有很多奇怪的东西,但这是它进入无限循环的地方:

picks_a_person = [A, B, C, D, E, F, G, H, I, J]
person_gets_picked = [A, B, C, D, E, F, G, H, I, J]
while len(order) < 10:
    a = person_gets_picked[random.randint(0, (len(person_gets_picked)-1))]
    if a != picks_a_person[0]:
        order.append(a)
        person_gets_picked.remove(a)
        del picks_a_person[0]
total.append(order)

让我们做一些橡皮鸭调试 - 当random.randint(0, (len(person_gets_picked)-1))连续九次返回大于0的数字时(最坏的情况),会发生什么?除person_gets_picked之外的所有A元素都会被删除并添加到order列表中(仍然在10元素下,以摆脱while循环)。< / p>

此时我们的状态为picks_a_person = [A]person_gets_picked = [A]。因此,random.randint(0, (len(person_gets_picked)-1))将始终返回0a将始终设置为A,而picks_a_person[0] == A if a != picks_a_person[0]将永远无法评估条件True因为order,因此A永远不会得到它的第10个元素,因此你得到了一个无限循环。

它甚至不必连续九个正数才能发生这种情况 - 所有需要发生的事情都是persons = [A, B, C, D, E, F, G, H, I, J] persons_num = len(persons) total = [random.sample(persons, persons_num) for _ in range(1000)] 仍然是最后一个两个选秀权并随意登陆另一个选项。

那么为什么不把你的整个循环写成:

{{1}}

你已经完成了。