我正在尝试编写Linq MinBy扩展方法
public static class Extensions
{
public static T MinBy<T>(this IEnumerable<T> source, Func<T,int> selector)
{
T min;
int? minKey = null;
foreach (var x in source)
{
var key = selector(x);
if (minKey == null || key < minKey)
{
minKey = key;
min = x;
}
}
if (minKey == null)
{
throw new ArgumentException("source should not be empty");
}
return min;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为我的逻辑是正确和可读的.但是我遇到了构建错误
使用未分配的局部变量'min'
我该怎么办?我可以测试变量是否已分配?
澄清:MinBy函数可以回答以下问题.哪个数字[-5,-2,3]具有最小的平方?
> new List<int>{-5,-2,3}.MinBy(x => x*x)
-2
Run Code Online (Sandbox Code Playgroud)
.NET的Min函数回答了一个不同的问题(这是最小的正方形)
> new List<int>{-5,-2,3}.Min(x …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一些与 Python Numpy.random.Choice相同的代码
关键部分是:probability
与 a 中每个条目相关的概率。如果未给出,则样本假定 a 中的所有条目均匀分布。
一些测试代码:
import numpy as np
n = 5
vocab_size = 3
p = np.array( [[ 0.65278451], [ 0.0868038725], [ 0.2604116175]])
print('Sum: ', repr(sum(p)))
for t in range(n):
x = np.random.choice(range(vocab_size), p=p.ravel())
print('x: %s x[x]: %s' % (x, p.ravel()[x]))
print(p.ravel())
Run Code Online (Sandbox Code Playgroud)
输出为:
Sum: array([ 1.])
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
[ 0.65278451 0.08680387 0.26041162]
Run Code Online (Sandbox Code Playgroud)
有时。
这里有一个分布,而且是部分随机的,但那里也有结构。 …