我已经开始做了。
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
函数。实际上,它返回的是一个整数数组(请参考 https:/numpy.orgdevdocsreferencerandomgeneratednumpy.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)