朱利安方式来做python的产量(和产量) [英] julian way to do python's yield (and yield from)
问题描述
什么是 julian 的方式来做 yield(和 yield from)as python do一个>?
What is julian way to do yield (and yield from) as python do?
我会尝试在 python 中添加小例子.
I will try to add small example in python.
想想 4x4 棋盘.找出长路棋王能做的每 N 步棋.不要浪费内存 -> 生成每条路径的生成器.
Think 4x4 chess board. Find every N moves long path chess king could do. Don't waste memory -> make generator of every path.
如果我们用数字在每个位置上签名:
if we sign every position with numbers:
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 16
点 0 有 3 个邻居 (1, 4, 5).我们可以为每个点找到每个邻居的表:
point 0 has 3 neighbors (1, 4, 5). We could find table for every neighbors for every point:
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]]
递归函数(生成器)从点列表或(...的生成器)点的生成器放大给定路径:
Recursive function (generator) which enlarge given path from list of points or from generator of (generator of ...) points:
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)
给定长度的每条路径的函数(生成器)
Function (generator) which give every path with given length
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
我们可以看到有 905776 条长度为 10 的路径:
We could see that there is 905776 paths with length 10:
sum(1 for i in paths(10))
Out[89]: 905776
在 ipython 中我们可以计时:
In ipython we could timeit:
%timeit sum(1 for i in paths(10))
1.21 s ± 15.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
我的 julia 实现很丑陋,而且要复杂得多.而且它似乎更慢.
My julia implementation is ugly and much more complicated. And it seems to be slower.
推荐答案
来自自述文件
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
这篇关于朱利安方式来做python的产量(和产量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!