Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia programming - creating a tuple from indices in a set

Tags:

tuples

julia

I have a set S={1,2,3}. I'm trying to create a tuple of the 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 in the following way.

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

But it doesn't give me the required result.What I'm getting 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,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 to get the required result?

like image 677
ccc Avatar asked Jan 03 '23 20:01

ccc


1 Answers

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 then pass this onto a set constructor; alternatively you can use a 'generator' directly:

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

What was I doing wrong though?

This part of the code:

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

doesn't do what you think it does. I think you intended E to be 'instantiated' as a 'set' object, to which you were then expecting to "append" elements by "assigning" them to E. (also, there's the issue of why you expected a normal element to act as a selection test, but whatever).

But clearly this doesn't work, because every time you assign something to E, you're replacing its previous contents with [a reference to] a new object.

If you wanted to approach this by carefully 'appending' your desired elements one-by-one, this is possible, but you should have done it like this:

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

(also note julia's special 'nested for loop' syntax here)

like image 76
Tasos Papastylianou Avatar answered Jan 31 '23 06:01

Tasos Papastylianou