[英]Efficient "destiny knot" partial inheritance function
在神奇寶貝游戲中(自第六代以來),命運之結是一種物品,在持有時會導致父母將其一些統計數據傳遞給它可能擁有的任何孩子。
我希望在 python 3 中創建一個 function ,它將創建一個數字列表的副本,該列表部分是隨機生成的,部分是從“父級”繼承的。 這是我的第一個實現:
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 減去那么多隨機數,但我還需要在正確的位置繼承它們,這為整個問題增加了一層復雜性。
最有效的方法是什么?
由於您使用的是 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. ])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.