回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>例如,对于<code>gr = np.array([5, 4, 3, 5, 2])</code>和<code>genx = np.array(["femy_gen_m", "my_gen_m", "my_gen_m", "femy_gen_m", "my_gen_m"])</code>,输出为<code>{'my_gen_m': 3.0, 'femy_gen_m': 5.0}</code>。暗示使用来自<code>numpy</code>的平均值</p>
<p>我为老师已经编写的单元测试编写函数,但函数处理速度较慢</p>
<p>附上我的代码如下</p>
<pre><code>from timeit import timeit
import numpy as np
#mycode
def mean_by_redneg(gr, genx):
result = {}
my_gen_m_sum, femy_gen_m_sum = [], []
for index, element in enumerate(genx):
if element == 'my_gen_m':
my_gen_m_sum.append(gr[index])
if element == 'femy_gen_m':
femy_gen_m_sum.append(gr[index])
result['my_gen_m'] = np.asarray(my_gen_m_sum).mean()
result['femy_gen_m'] = np.asarray(femy_gen_m_sum).mean()
return result
#check the function
def test(gr, genx, outp):
ret = mean_by_redneg(np.array(gr), np.array(genx))
assert np.isclose(ret['femy_gen_m'], outp['femy_gen_m'])
assert np.isclose(ret['my_gen_m'], outp['my_gen_m'])
test([5, 4, 3, 5, 2], ["femy_gen_m", "my_gen_m", "my_gen_m", "femy_gen_m", "my_gen_m"], {'my_gen_m': 3.0, 'femy_gen_m': 5.0})
test([1, 0] * 10, ['femy_gen_m', 'my_gen_m'] * 10, {'femy_gen_m': 1, 'my_gen_m': 0})
test(range(100), ['femy_gen_m', 'my_gen_m'] * 50, {'femy_gen_m': 49.0, 'my_gen_m': 50.0})
test(list(range(100)) + [100], ['my_gen_m'] * 100 + ['femy_gen_m'], {'my_gen_m': 49.5, 'femy_gen_m': 100.0})
def bm_test(a, b):
xx = 0
yy = 0
im = 0
fi = 0
for x, y in zip(a, b):
if x != y:
xx += x
yy += x
im += 1
fi += 1
return xx + yy
N = int(1E5)
gr = np.array([1.1] * N + [2.2] * N)
genx = np.array(['my_gen_m'] * N + ['femy_gen_m'] * N)
bm = timeit("assert np.isclose(mean_by_redneg(gr, genx)['my_gen_m'], 1.1)",
"from __main__ import np, mean_by_redneg, gr, genx",
number=1)
reference_bm = timeit("bm_test(gr, genx)",
"from __main__ import bm_test, gr, genx",
number=1)
assert reference_bm > bm * 10, "too slow"
</code></pre>
<p>你知道如何更快地完成这项工作吗?
p、 谢谢你抽出时间</p>