我有一些python代码,我试图移植到Julia学习这种可爱的语言.我在python中使用了生成器.移植后,在我看来(此时此刻)Julia在这个区域真的很慢!
我将部分代码简化为本练习:
想想4x4棋盘.找到每一个N-move长路,国际象棋王可以做到.在这个练习中,国王不允许在一条路径中的同一位置跳跃两次.不要浪费记忆 - >制作每条路径的发电机.
算法非常简单:
如果我们用数字签署每个位置:
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).我们可以为每个点找到每个邻居的表:
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, …Run Code Online (Sandbox Code Playgroud) 我该如何解析更多代码?
这是有效的:
julia> eval(parse("""print("O");print("K")"""))
OK
Run Code Online (Sandbox Code Playgroud)
这不起作用:
julia> eval(parse("""print("N");
print("O")"""))
ERROR: ParseError("extra token after end of expression")
Stacktrace:
[1] #parse#235(::Bool, ::Function, ::String) at ./parse.jl:237
[2] parse(::String) at ./parse.jl:232
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果我逐行尝试,我还有其他问题.例如:
julia> parse("""for i in 1:3""")
:($(Expr(:incomplete, "incomplete: premature end of input")))
Run Code Online (Sandbox Code Playgroud)
虽然:
julia> eval(parse("""for i in 1:2
println(i)
end"""))
1
2
Run Code Online (Sandbox Code Playgroud) 什么是像 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, …Run Code Online (Sandbox Code Playgroud) 在这里我期望Int类型但得到Float:
julia> function test()
i::Int = 3.0
end
test (generic function with 1 method)
julia> typeof(test())
Float64
Run Code Online (Sandbox Code Playgroud)
在这种情况下,返回类型是Int:
julia> function test()
i::Int = 3.0
i
end
test (generic function with 1 method)
julia> typeof(test())
Int64
Run Code Online (Sandbox Code Playgroud)
这是正确的行为还是错误?
julia ×4