问题描述
儒略(julian)产生(和产生)的方法是什么(与python一样?
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
这篇关于朱利安(Julian)做python(' s)产量的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!