[英]Julia Iterator product and filter
我需要找到解決a + b + c = 15(或其他)的3個數組的解決方案
到目前為止,我堅持使用以下代碼:
A = 1:10
B = 1:10
C = 1:10
possibilities = Iterators.product(A, B, C)
solutions = Iterators.filter((a, b, c) -> a + b + c == 15, possibilities)
sol = collect(solutions)
for (a, b, c) in sol
println(a, " ", b, " ", c)
end
我從編譯器得到這個錯誤:
> ERROR: LoadError: MethodError: no method matching
> (::##1#2)(::Tuple{Int64,Int64,Int64}) Closest candidates are:
> #1(::Any, !Matched::Any, !Matched::Any) at /home/cg/root/7729001/main.jl:6 Stacktrace: [1] start_filter(::##1#2,
> ::Base.Iterators.Prod{UnitRange{Int64},Base.Iterators.Prod2{UnitRange{Int64},UnitRange{Int64}}})
> at ./iterators.jl:272 [2] _collect(::UnitRange{Int64},
> ::Base.Iterators.Filter{##1#2,Base.Iterators.Prod{UnitRange{Int64},Base.Iterators.Prod2{UnitRange{Int64},UnitRange{Int64}}}},
> ::Base.HasEltype, ::Base.SizeUnknown) at ./array.jl:408 [3]
> collect(::Base.Iterators.Filter{##1#2,Base.Iterators.Prod{UnitRange{Int64},Base.Iterators.Prod2{UnitRange{Int64},UnitRange{Int64}}}})
> at ./array.jl:397 while loading /home/cg/root/7729001/main.jl, in
> expression starting on line 7
也許你有一個想法來解決這個或解決問題的方法。
可能性的元素是元組。 在此代碼中將每個視為x
:
A = 1:10
B = 1:10
C = 1:10
possibilities = Iterators.product(A, B, C)
# The change is in this line
solutions = Iterators.filter(x -> x[1] + x[2] + x[3] == 15, possibilities)
sol = collect(solutions)
for (a, b, c) in sol
println(a, " ", b, " ", c)
end
另一個答案正確地診斷出你需要處理一個元組,而不是三個參數。
在Julia 1.0中,你也可以在lambda中使用參數解構 ,但語法並不像它可能那么明顯:
Iterators.filter(((a, b, c),) -> a + b + c == 15, possibilities)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.