Julia: 从set 、setdiff和 setdiff!说起

来源:互联网 发布:单片机上拉电阻原理图 编辑:程序博客网 时间:2024/04/27 13:42

一、Set : 没有顺序,有些象Dict()
julia> b=Set{Int}[] # 不能用push!
0-element Array{Set{Int64},1}
julia> push!(b,Set{1})
MethodError(convert,(Set{Int64},Set{1}))
julia> push!(b,1)
MethodError(convert,(Set{Int64},1))
 
julia> b=Set{Int}() # 可以用push!
Set{Int64}()
julia> push!(b,1)
Set{Int64}(1)
julia> push!(b,2)
Set{Int64}(2,1)
julia> push!(b,3)
Set{Int64}(2,3,1)

二、setdiff :二个集合的不同元素(在一个中,但不在另一个中)
 Construct the set of elements in s1 but not s2.Maintainsorder with arrays.
julia> A = [1,2,3,0]; B = [2,3,4];
julia> setdiff(A, B) # 找出在A中,但是不在B中的元素, 按A中顺序排列
 2-element Array{Int32,1}:
 1
 0
# 注意,并不能进行以下操作,认为可以找到二者的不同!
julia> setdiff(Set(A), Set(B)) # 注意,这二个的不同元素,并不相交,所以仍为前者!
Set{Array{Int64,1}}([1,2,3,0])

# 根本原因是:Set(A) 并不是Set{Int64}类型!
julia> Set(A)
Set{Array{Int64,1}}([1,2,3,0])


三、setdiff! : setdiff!(s, iterable) :Remove each elementof iterable from set s in-place. 
因此,前面一个参数必须是Set !
# 操作1
julia> b
Set{Int64}(2,3,1)

julia> setdiff!(b,[1 2])  # 操作后,b: 为只有一个3元素的Set!
Set{Int64}(3)

# 操作2
julia> A =Set([1 2 3])
Set{Array{Int64,2}}(1x3 Array{Int64,2}:1  2  3)
julia> B=Set([2 3 4])
Set{Array{Int64,2}}(1x3 Array{Int64,2}: 2  3  4)
julia> setdiff!(A,B)
Set{Array{Int64,2}}(1x3 Array{Int64,2}:1  2  3)
# 操作3
julia> setdiff!(B,[1,2])
Set{Array{Int64,2}}(1x3 Array{Int64,2}: 2  3  4)

# error
julia> setdiff!([1 2 3],[1,2])
MethodError(setdiff!,(1x3 Array{Int64,2}:1  2  3,[1,2]))
 
# 举例:一个求质数的函数(说明:来自于转载)
# 一个大于1的自然数,除了1和它本身外,不能被其他自然数整除(除0以外)的数称之为素数(质数);
function get_primes(n)
   numbers::Set{Int} = Set(2:n)
   primes::Array{Int64,1} = []
   while !isempty(numbers)
      p = minimum(numbers)
      push!(primes,p);
      setdiff!(numbers,Set(p:p:n))
   end
   return primes
end

0 0