构建一个函数来掷出由 `f` 提供的一系列骰子,并计算结果中最大数字为 `x_max` 的概率

Build a function to roll a list of dice provided by `f`, and calculate the probability that the largest number among the outcomes is `x_max`

我已经做到了:

def largest_face(f, x_max):
    # inputs: f is a list of integers and x_max is an integer
    # output: a variable of type 'float'

    #generate len(f) random throws of (len(f)) dice with number of faces defined by f 
    outcomes= []
    for i in f:
        out = 1 + np.random.randint(i, size = len(f) )
        outcomes.append(out) #something wrong here as it works when testing separately but doesnt in the function, see below

    #calculate probabilty 
    proba = []
    for i in outcomes:
        if x_max >i:
            pass
        elif x_max<=i:
            a = x_max/i
            b =(x_max-1)/i
            c = a-b
            proba.append(c) 
    p=np.cumprod(proba)[-1]

    return p

但是,如果 运行 两个部分(生成结果和计算概率)工作得很好,当我 运行 函数时它会导致错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-71-af4c5a7929d0> in <module>
----> 1 c =largest_face([7,5],5)
      2 #c
      3 outcomes

<ipython-input-69-52e99563de50> in largest_face(f, x_max)
     13     proba = []
     14     for i in outcomes:
---> 15         if x_max >i:
     16             pass
     17         elif x_max<=i:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如有任何帮助,我们将不胜感激!

问题出在您的 np.random.randint 函数上。它实际上是returns一个整数数组(参考https://numpy.org/devdocs/reference/random/generated/numpy.random.randint.html

我试图更正您的实现:

import numpy as np
def largest_face(f, x_max):
    # inputs: f is a list of integers and x_max is an integer
    # output: a variable of type 'float'

    #generate len(f) random throws of (len(f)) dice with number of faces defined by f 
    outcomes= []
    for i in f:
        out = 1 + np.random.randint(i, size = len(f) )
        outcomes.append(out) #something wrong here as it works when testing separately but doesnt in the function, see below
    #calculate probabilty 
    proba = []
    for array in outcomes:
      if x_max<=max(array):
            a = x_max/array
            b =(x_max-1)/array
            c = a-b
            proba.append(c) 
    p=np.cumprod(proba)[-1]

    return p
if __name__=='__main__':
    print largest_face([7,5],5)