朱利安方式来做python的产量(和产量)

Lis*_*iso 5 julia

什么是像 python 那样做 yield(和 yield from)的 julian 方法?

编辑:我会尝试在 python 中添加小例子。

想想 4x4 国际象棋棋盘。找到棋王可以做的每N步长路径。不要浪费内存-> 生成每条路径。

如果我们用数字签署每个职位:

0  1  2  3
4  5  6  7
8  9  10 11
12 13 14 16
Run Code Online (Sandbox Code Playgroud)

点 0 有 3 个邻居(1、4、5)。我们可以为每个点找到每个邻居的表格:

0  1  2  3
4  5  6  7
8  9  10 11
12 13 14 16
Run Code Online (Sandbox Code Playgroud)

递归函数(生成器)从点列表或(...的生成器)点的生成器放大给定路径:

NEIG = [[1, 4, 5], [0, 2, 4, 5, 6], [1, 3, 5, 6, 7], [2, 6, 7], [0, 1, 5, 8, 9], [0, 1, 2, 4, 6, 8, 9, 10], [1, 2, 3, 5, 7, 9, 10, 11], [2, 3, 6, 10, 11], [4, 5, 9, 12, 13], [4, 5, 6, 8, 10, 12, 13, 14], [5, 6, 7, 9, 11, 13, 14, 15], [6, 7, 10, 14, 15], [8, 9, 13], [8, 9, 10, 12, 14], [9, 10, 11, 13, 15], [10, 11, 14]]
Run Code Online (Sandbox Code Playgroud)

给定长度的每条路径的函数(生成器)

def enlarge(path):
    if isinstance(path, list):
        for i in NEIG[path[-1]]:
            if i not in path:
                yield path[:] + [i]
    else:
        for i in path:
            yield from enlarge(i)
Run Code Online (Sandbox Code Playgroud)

我们可以看到有 905776 条长度为 10 的路径:

def paths(length):
    steps = ([i] for i in range(16))  # first steps on every point on board
    for _ in range(length-1):
        nsteps = enlarge(steps)
        steps = nsteps
    yield from steps
Run Code Online (Sandbox Code Playgroud)

在 ipython 中,我们可以计时:

sum(1 for i in paths(10))
Out[89]: 905776
Run Code Online (Sandbox Code Playgroud)

我的 julia 实现很丑陋,而且要复杂得多。而且好像比较慢。

ggg*_*ggg 3

查看ResumableFunctions.jl

来自自述文件

using ResumableFunctions

@resumable function fibonnaci(n::Int) :: Int
  a = 0
  b = 1
  for i in 1:n-1
    @yield a
    a, b = b, a+b
  end
  a
end

for fib in fibonnaci(10)
  println(fib)
end
Run Code Online (Sandbox Code Playgroud)