在精灵游戏(从第六代起),命运结是一个项目,当持有,将导致父母传递它的一些统计数字给任何孩子,它可能有。
我希望在python 3中创建一个函数,它将创建一个数字列表的副本,该列表部分是随机生成的,部分是从“父”继承的。以下是我的第一个实现:
def destiny_knot(parent, prob):
child = []
for n in parent :
if np.random.rand(1)<prob :
child.append(n)
else :
child.append(np.random.normal())
return child
当运行时,它的工作原理是:
foo = range(10)
destiny_knot(foo, 0.5)
[3.7189086135642975, 1, 0.6303126955135048, -0.9230447017112412, 4, 5, 6, 0.8633075878923896, 0.4633879779484653, -1.5192557497361636]
但是,对我来说很明显,这需要很长的时间才能真正实现我正在寻找的用途:我的每个列表都是数千个元素,如果不是几十万元素的话,我的目标是生成数千个元素。
我在考虑确定一些将被继承的元素,生成N减去那么多随机数,但我也需要在正确的位置继承它们,这给整个问题增加了一层复杂性。
做这件事最有效的方法是什么?
发布于 2021-05-05 15:40:45
由于您使用的是NumPy:
def destiny_knot(parent: np.ndarray, prob: float):
child = parent.copy() # Inherit everything
# Mask for future random numbers
am_I_random = np.random.rand(parent.size) > prob
# Generate random numbers and put them into `child`
# according to the mask `am_I_random`
child[am_I_random] = np.random.normal(size=am_I_random.sum())
return child
确保parent
是一个浮点数数组,否则np.random.normal(size=am_I_random.sum())
返回的浮点数将转换为整数或任何类型的parent
。
示例运行:
>>> parent = np.asfarray([1,2,3,6,4,2,5])
>>> destiny_knot(parent, .7)
array([ 1. , 2. , 3. , 6. , -1.10456035,
2. , 2.43449116])
>>> destiny_knot(parent, .5)
array([-0.67617249, 2. , 3. , -2.11637063, 0.19032201,
2. , 5. ])
https://stackoverflow.com/questions/67404404
复制相似问题