哈佛cs109 homework0 switch_guesses

时间:2015-03-18 22:49:45

标签: 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

不太明白这是如何工作的,任何人都可以帮忙解释一下吗? 谢谢!

  

提示:

     

切换后返回新门。应该是两者都不同   猜测和山羊门

     

实施例

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

2 个答案:

答案 0 :(得分:2)

由于交换机字典的第4个条目中的错误,您可能在理解此示例时遇到一些麻烦。它应该如下:

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

答案 1 :(得分:1)

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

  

鉴于您猜到guesses[i]并且goatdoors[i]后面有一只山羊,您应该切换并选择门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