Ask Your Question

From indexed variables to strings

asked 2020-10-25 18:40:37 +0200

Cyrille gravatar image

I can easily generate a list of variables with

xx = var("x", n=10, latex_name="x")

but I have many questions about this

1) nc is the number of variables needed. Say I need variables indexed from 10 to 20, not from 0 to 20. Am I obliged to generate all 20 variables and let appart the 10 firsts (I have found nothing on options like n=, could it be a range ?). 2) if I have generated the following list x=[x_1, x_2, x_3, x_4, x_5] how may i transform it in a list of strings x=['x_1', 'x_2', 'x_3', 'x_4', 'x_5'] 3) and what if I need to change the name of certain variable as 'x_3'-->'\\epsilon_2'

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2020-10-25 19:41:15 +0200

nbruin gravatar image

var accepts a list of strings, so if you want to make a list of custom variable names, you're good if you can generate the list of string names. For instance,

var(['x_{}'.format(i) for i in range(10,21)])

Works fine. I don't know if there's a way of letting latex_name work for a list of variables, but if you're going to have to write a for anyway, why not pull it out and create the variable names one-by-one?

for i in range(3,5):
    var("x_{}".format(i), latex_name="\epsilon_{}".format(i-1))

At some point it just becomes much easier and flexible to leverage that python is a full-featured programming language than to rely on the built-in options designed to allow people to defer learning for accomplishing simple, standardized tasks.

Generally, sage offers simple, modular building blocks which you can arrange yourself to build programs for more complex tasks. Sometimes, sage also offers more byzantine options; usually put in because it was found a lot of people often used a particular combination of simple building blocks (or because someone with enough energy to implement it put it in so that they could save a few lines of code in an introductory text book). If you find yourself asking how to generalize a certain compound construct, you should probably ask yourself how you'd build the original compound construct in the first place and then generalize from there.

edit flag offensive delete link more


There is a little pb with the answer for indices greater or equal to 10. One should modify the answer to var(['x_{}'.format({i}) for i in range(10,21)])

Cyrille gravatar imageCyrille ( 2020-11-18 09:26:54 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-10-25 18:40:37 +0200

Seen: 44 times

Last updated: Oct 25 '20