# Can I show ordered sets in order?

I'm using SageTex to generate random algebra tests, with an answer key at the end. To have my students show they understand roster notation for sets, I'm having them write the set of all two-digit multiples of n for some number n in {2, 3, 4, ... 9}. Asking the question isn't hard. But in generating the answer key, the set shows up in random order. I know it's still the same set, of course, but it's less intuitive to interpret. It seems like Sage is going out of it's way to randomize the set. Here's some minimal working code:

n = Set(range(2, 10)).random_element()
X = Set()
for i in range(10, 100):
if i % n == 0:
X = X.union(Set([i]))
show(n)
show(X)


This shows, for example:

8

{32, 64, 48, 40, 80, 96, 16, 24, 56, 72, 88}

Is there some way to have Sage show the elements of the set in order?

edit retag close merge delete

A less than 100% satisfactory workaround is to convert the Set to a list, sort the list, then show the list. This works for me ok, but it defeats my purpose if I share an answer key with my students and the answer key has the wrong notation (namely the square brackets of lists instead of the curly braces of sets).

( 2016-08-08 02:31:39 +0200 )edit

A better solution I found is to just LaTeX the parts I want. This makes the answer key look like an answer the student should give. After converting the Set X to the list X, I then put the code below in the answer key.

$\{\sage{X[0]}, \sage{X[1]},\sage{X[2]},... , \sage{X[len(X)-1]}\}$


I'm still curious about whether one can show sets in order, so for now I'll leave the question open.

( 2016-08-08 02:42:35 +0200 )edit

Sort by » oldest newest most voted

You can modify X before printing it, sorting it (as you suggested) and then changing the brackets:

s = str(sorted(X))
s = s.replace('[', '\\{')
s = s.replace(']', '\\}')


Then print s using

\sagestr{s}

more

There are various set-like objects in sage. Maybe you should try "set" instead.

sage: S = Set([5,6,44])
sage: S
{44, 5, 6}
sage: S = set([5,6,44])
sage: S
{5, 6, 44}
sage: S = frozenset([5,6,44])
sage: S
frozenset({5, 6, 44})

more