nes*_*983 12 wolfram-mathematica
你可以yield在Mathematica中做类似Python的声明,以创建生成器吗?请参阅此处的概念.
更新
这里是一个我的意思的例子,迭代所有的排列,只使用O(n)空间:(在Sedgewick的算法书中的算法):
gen[f_, n_] := Module[{id = -1, val = Table[Null, {n}], visit},
visit[k_] := Module[{t},
id++; If[k != 0, val[[k]] = id];
If[id == n, f[val]];
Do[If[val[[t]] == Null, visit[t]], {t, 1, n}];
id--; val[[k]] = Null;];
visit[0];
]
Run Code Online (Sandbox Code Playgroud)
然后把它称为:
gen[Print,3],打印所有6个长度为3的排列.
正如我之前所说,使用Compile会给出更快的代码.使用fxtbook中的算法,以下代码在字典顺序中生成下一个分区:
PermutationIterator[f_, n_Integer?Positive, nextFunc_] :=
Module[{this = Range[n]},
While[this =!= {-1}, f[this]; this = nextFunc[n, this]];]
Run Code Online (Sandbox Code Playgroud)
以下代码假定我们运行版本8:
ClearAll[cfNextPartition];
cfNextPartition[target : "MVM" | "C"] :=
cfNextPartition[target] =
Compile[{{n, _Integer}, {this, _Integer, 1}},
Module[{i = n, j = n, ni, next = this, r, s},
While[Part[next, --i] > Part[next, i + 1],
If[i == 1, i = 0; Break[]]];
If[i == 0, {-1}, ni = Part[next, i];
While[ni > Part[next, j], --j];
next[[i]] = Part[next, j]; next[[j]] = ni;
r = n; s = i + 1;
While[r > s, ni = Part[next, r]; next[[r]] = Part[next, s];
next[[s]] = ni; --r; ++s];
next
]], RuntimeOptions -> "Speed", CompilationTarget -> target
];
Run Code Online (Sandbox Code Playgroud)
然后
In[75]:= Reap[PermutationIterator[Sow, 4, cfNextPartition["C"]]][[2,
1]] === Permutations[Range[4]]
Out[75]= True
Run Code Online (Sandbox Code Playgroud)
这显然比原始gen功能更好.
In[83]:= gen[dummy, 9] // Timing
Out[83]= {26.067, Null}
In[84]:= PermutationIterator[dummy, 9, cfNextPartition["C"]] // Timing
Out[84]= {1.03, Null}
Run Code Online (Sandbox Code Playgroud)
使用Mathematica的虚拟机速度并不慢:
In[85]:= PermutationIterator[dummy, 9,
cfNextPartition["MVM"]] // Timing
Out[85]= {1.154, Null}
Run Code Online (Sandbox Code Playgroud)
当然,这远不是C代码实现,而是提供了超过纯顶级代码的大幅加速.