Ask Your Question
0

Index problem

asked 2021-06-29 22:48:32 +0200

Cyrille gravatar image

I am absolutely confused to ask a question that I think to have asked a lot of time but each time I am confused.

I have this simple code

x = list(var('x_%i' % i) for i in (0..1))
show(x)
Ineq = [x[1] + x[0] <= -2, x[1] >=0,x[0] >=0]
show(Ineq)
type(Ineq[0])
sol0=solve_ineq([x[0] + x[1] <= -2, x[1] >=0,x[0] >=0],[x[0],x[1]])
sol0

If I replace (0..1) by (1..2) whith the correction for the x[i], I have an error of the type list index out of range. Why ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-06-30 00:39:18 +0200

The line x = list(var('x_%i' % i) for i in (0..1)) defines x to be a list, and no matter what numbers you put in (m..n), lists in Python are indexed starting at 0. For example:

sage: x = list(var('x_%i' % i) for i in (1..2))                                           
sage: x                                                                                   
[x_1, x_2]
sage: x[0]                                                                                
x_1
sage: x[1]                                                                                
x_2
sage: x[2]                                                                                
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-7-481b12fa0bac> in <module>
----> 1 x[Integer(2)]

IndexError: list index out of range

That is, x[0] refers to the 0th element of the list x; the part of the command for i in (1..2) doesn't affect the list indexing. You could use a dictionary if you want different indexing:

sage: x = dict((i, var('x_%i' % i)) for i in (1..2))                                      
sage: x  # the numbers 1 and 2 are the keys: the allowable indices
{1: x_1, 2: x_2}
sage: x[1]                                                                                
x_1
sage: x[2]                                                                                
x_2
edit flag offensive delete link more

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

Stats

Asked: 2021-06-29 22:48:32 +0200

Seen: 54 times

Last updated: Jun 30 '21