How to take indices and name of a variable in Sage?

455 Views Asked by At

I define the following in Sage.

rank=8
R=PolynomialRing(QQ, 'a' ,rank+1)
a=R.gens()

I would like to define a function f which returns the index of a[3]: f(a[3])=3 and define another function g such that g(a[3])=a. How to do this in Sage? Thank you very much!

2

There are 2 best solutions below

0
On BEST ANSWER

This answer draws on the one by Alex J Best for defining f, but also defines g.

Define a multivariate polynomial ring and its generator tuple:

sage: R = PolynomialRing(QQ, 'a', 4)
sage: R
Multivariate Polynomial Ring in a0, a1, a2, a3 over Rational Field
sage: a = R.gens()
sage: a
(a0, a1, a2, a3)

Consider one of the generators (or "indeterminates", or "variables"):

sage: p = a[2]
sage: p
a2

To get its index in the generator tuple:

sage: a.index(p)
2

This can be made into the function f requested in the question:

sage: f = a.index
sage: f(p)
2

The above is tied to the definition of a; more generally:

def f(p):
    r"""
    Return the index of this generator of a polynomial ring.
    """
    return p.parent().gens().index()

What function g the question requests is not entirely clear.

If we want g(a[2]) to return the string 'a':

def g(p):
    r"""
    Return the generator name stripped of its index.
    """
    return ''.join(c for c in str(p) if not c.isdigit())

With that definition:

sage: p = a[2]
sage: aa, k = g(p), f(p)
sage: aa
'a'
sage: k
2
sage: ak = aa + str(k)
sage: ak
'a2'
sage: ak == str(p)
True
sage: R(ak) == p
True

If instead we want g(a[2]) to return the tuple R.gens():

def g(p):
    r"""
    Return the tuple of generators of the parent polynomial ring.
    """
    return p.parent().gens()

With that definition:

sage: p = a[2]
sage: aa, k = g(p), f(p)
sage: aa
(a0, a1, a2, a3)
sage: k
2
sage: ak = aa[k]
sage: ak
a2
sage: ak == p
True
1
On

This is something generic about lists in python so

a.index(a[3])

for the first (you can write f = a.index if you like), and for the second if you really want a function rather than using [3] you can do

def g(n):
    return a[n]