gpt4 book ai didi

wolfram-mathematica - Mathematica 中的产量

转载 作者:行者123 更新时间:2023-12-04 01:08:48 25 4
gpt4 key购买 nike

你能做类似 Python 的 yield 的事情吗? Mathematica 中的语句,以便创建生成器?见例如here为概念。

更新
这是我的意思的一个例子,迭代所有排列,只使用 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];
]

然后称之为:
gen[Print,3] ,打印长度为 3 的所有 6 个排列。

最佳答案

正如我之前所说,使用 Compile将给出更快的代码。使用来自 fxtbook 的算法,以下代码按字典顺序生成下一个分区:

PermutationIterator[f_, n_Integer?Positive, nextFunc_] := 
Module[{this = Range[n]},
While[this =!= {-1}, f[this]; this = nextFunc[n, this]];]

以下代码假设我们运行版本 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
];

然后
In[75]:= Reap[PermutationIterator[Sow, 4, cfNextPartition["C"]]][[2, 
1]] === Permutations[Range[4]]

Out[75]= True

这在性能上明显优于原始 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}

使用 Mathematica 的虚拟机也不会慢很多:
In[85]:= PermutationIterator[dummy, 9, 
cfNextPartition["MVM"]] // Timing

Out[85]= {1.154, Null}

当然,这与 C 代码实现相去甚远,但与纯顶级代码相比,它提供了显着的加速。

关于wolfram-mathematica - Mathematica 中的产量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1165742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com