我所追求的算法有一个很好的实现here https://stackoverflow.com/questions/39192777/python-split-a-list-into-n-groups-in-all-possible-combinations-of-group-length-a/ (by @懒狗 https://stackoverflow.com/users/6732794/lazy-dog)。然而,我在 C# 中需要这个,并且由于 C# 缺乏yield from
也许还有我自己的愚蠢。
这是我目前拥有的:
public static IEnumerable<ArrayList> sorted_k_partitions(int[] seq, int k) {
var n = seq.Length;
var groups = new ArrayList(); //a list of lists, currently empty
IEnumerable<ArrayList> generate_partitions(int i) {
if (i >= n) {
// this line was the bug, was not creating a
// deep clone of the list of lists
// yield return new ArrayList(groups);
yield return new ArrayList(groups.ToArray().Select(g => ((List<int>)g).ToList()));
// Ugly but that is because we are using ArrayList
// Using proper List<List<int>> cleans this up significantly
}
else {
if (n - i > k - groups.Count)
foreach (List<int> group in new ArrayList(groups)) {
group.Add(seq[i]);
// yield from generate_partitions(i + 1);
foreach (var d in generate_partitions(i + 1)) {
yield return d;
}
group.RemoveAt(group.Count - 1);
}
if (groups.Count < k) {
groups.Add(new List<int> {seq[i]});
foreach (var d in generate_partitions(i + 1)) {
// things start breaking down here, as this yield return
// appears to release flow control and we then get the
// yield return above. I have debuged this and the python
// version and the python version does not do this. Very hard
// to explain considering I don't fully understand it myself
yield return d;
}
groups.RemoveAt(groups.Count - 1);
}
}
}
return generate_partitions(0);
// don't worry about the sorting methods in the python
// version, not needed
}
任何人都可以看到任何明显的错误,我确信我对Python缺乏理解yield from
协程在这里伤害了我。
编辑:发现错误,在上面添加评论
你在这里有什么行为?
在我看来yield return generate_partitions(i + 1);
而不是 foreach 循环应该可以正常工作。它只会使用新值递归调用该函数i+1
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)