哈佛cs109家庭作业

2024-09-30 14:15:34 发布

您现在位置:Python中文网/ 问答频道 /正文

def switch_guess(guesses, goatdoors):

    result = np.zeros(guesses.size)
    switch = {(0, 1): 2, (0, 2): 1, (1, 0): 2, (1, 2): 1, (2, 0): 1, (2, 1): 0}
    for i in [0, 1, 2]:
        for j in [0, 1, 2]:
            mask = (guesses == i) & (goatdoors == j)
            if not mask.any():
                continue
            result = np.where(mask, np.ones_like(result) * switch[(i, j)], result)
    return result

我不太明白这是怎么回事,有人能解释一下吗? 谢谢!你知道吗

hints:

Returns The new door after switching. Should be different from both guesses and goatdoors

Examples

>>> print switch_guess(np.array([0, 1, 2]), np.array([1, 2, 1]))
>>> array([2, 0, 0])
"""

Tags: inforsizeifdefnpzerosnot
2条回答

由于switch字典的第4个条目中的错误,您可能在理解此示例时遇到一些困难。具体如下:

switch = {(0, 1): 2, (0, 2): 1, (1, 0): 2, (1, 2): 0, (2, 0): 1, (2, 1): 0}

我在源代码中添加了一些注释,这些注释解释了我对代码的理解。它看起来确实很像蒙蒂霍尔实验,所以我猜这个函数基本上是这样的:

Given that you guessed guesses[i] and there is a goat behind goatdoors[i], you should switch and pick door results[i].

如果我理解正确的话,解决这个问题似乎也有点复杂。你知道吗

def switch_guess(guesses, goatdoors):
    # Initialise result to an array of zeros, the same size as the guesses array
    result = np.zeros(guesses.size)
    # Create a dictionary to be used later in determining the values of result.
    switch = {(0, 1): 2, (0, 2): 1, (1, 0): 2, (1, 2): 1, (2, 0): 1, (2, 1): 0}
    for i in [0, 1, 2]:
        for j in [0, 1, 2]:
            # Create a mask, which is True when the corresponding elements of 
            # guesses and goatdoors are both equal to i and j, respectively.
            mask = (guesses == i) & (goatdoors == j)
            # If no elements of mask are true, go to the next loop iteration (of 
            # the j loop).
            if not mask.any():
                continue
            # For each element of result, if the corresponding element of mask
            # is True, set the element of result to 1 * switch[(i, j)], otherwise
            # leave it unchanged.
            result = np.where(mask, np.ones_like(result) * switch[(i, j)], result)
    return result

相关问题 更多 >

    热门问题