Julia Programming - Creating a Tuple of Indexes in a Set

I have a lot of S = {1,2,3}. I am trying to create a tuple of form (i, j, 1) for which I and j are elements of S. When S = {1,2,3}, my set of tuples (say E) should be {(1,2,1 ), (2,1,1), (1,3,1), (3,1,1), (3,2,1), (2,3,1)}. I tried as follows.

for i in S for j in S E = Set() E = [(i,j,1),(j,i,1), i!=j] print(E) end end 

But this does not give me the desired result. What i get is

Any [(2,2,1), (2,2,1), false] Any [(2,3,1), (3,2,1), true] Any [(2,1, 1), (1,2,1), true] Any [(3,2,1), (2,3,1), true] Any [(3,3,1), (3,3,1), false] Any [(3,1,1,1), (1,3,1), true] Any [(1,2,1), (2,1,1), true] Any [(1,3, 1), (3,1,1) true] Any [(1,1,1), (1,1,1) false]

Can someone please help me get the desired result?

+5
source share
2 answers

A more general solution might be:

 julia> [(first(i)..., last(i)...) for i in Base.product(permutations(1:4, 3), [(5,6)])] 24×1 Array{Tuple{Int64,Int64,Int64,Int64,Int64},2}: (1,2,3,5,6) (1,2,4,5,6) (1,3,2,5,6) (1,3,4,5,6) (1,4,2,5,6) (1,4,3,5,6) (2,1,3,5,6) (2,1,4,5,6) (2,3,1,5,6) (2,3,4,5,6) (2,4,1,5,6) (2,4,3,5,6) (3,1,2,5,6) (3,1,4,5,6) (3,2,1,5,6) (3,2,4,5,6) (3,4,1,5,6) (3,4,2,5,6) (4,1,2,5,6) (4,1,3,5,6) (4,2,1,5,6) (4,2,3,5,6) (4,3,1,5,6) (4,3,2,5,6) 
+3
source

You can achieve what you want with a list comprehension :

 [(i,j,1) for i in S for j in S if i != j] 

Note that this gives you an array, but you can pass this to the set constructor; Alternatively, you can use generator directly:

 Set( (i,j,1) for i in S for j in S if i != j ) 

What did I do wrong though?

This piece of code:

 E = Set() E = [(i,j,1),(j,i,1), i!=j] 

Don't do what you think. I think you intend E be "instance" as a "set" object, to which you then expected to "add" elements by "assigning" them to E. (there is also a question why you expected a normal element to perform a selection test, but whatever).

But this clearly does not work, because every time you assign something to E , you replace its previous contents with a link [link to] a new object.

If you want to get closer to this by carefully adding your desired items one by one, this is possible, but you should do it this way:

 E = Set() for i in S, j in S if i != j push!(E, (i,j,1), (j,i,1)); end end 

(also note the syntax of julia special 'inested for loop')

+7
source

Source: https://habr.com/ru/post/1268974/


All Articles