I’m trying to order elements (Sym) from a Tuple. I’ve tried several codes but nothing works.
I will be grateful if anyone can help.
using SymPy
using LinearAlgebra
a1 = [Sym("a_$i^$j") for i=1 for j=1:2]
a2 = [Sym("a_$i^$j") for i=2 for j=1:2]
A = [a1,a2] # conjunto de todas as ações
S = vec(collect(Base.product(A...))) #Cartesian product
SymPy.sort!(S, by = x -> S[1])
sort also accepts a keyword argument lt (standing for less-than) which defaults to isless. Since isless doesn’t seem to be useful for Syms, you can set a comparison manually. If you want it to follow the string order, you can do:
The way you used is fine, but note that you can just use string(...), rather than String(Symbol(...)) as I did in my second example.
However, just to demonstrate that you can in fact sort by any column:
# with `lt`
sort(S, by = x->x[2], lt = (x, y) -> string(x) < string(y))
# or using composition in `by`
sort(S, by = string ∘ (x -> x[2]))
So anything is possible
Also, it is now apparent that what you want is simply:
sort(S, by = string)
which will sort the entries in lexicographic order of their strings, which in this case will sort by first character, then second character, then third, and so on. So if your variables are named as you’ve shown, this will work.