Processing math: 100%
Ask Your Question
0

How to permute strings from two lists (or vectors)

asked 4 years ago

Cyrille gravatar image

Suppose I have to vector of variables

NB=vector(var('x', n=3, latex_name='x'))
B=vector(var('y', n=4, latex_name='ϵ'))

I would like to construct a function say BNB(vec1, vec2, pr, pc) such that when applied to B and for legitiamte values --- i.e. : here, NB should be less than 3 and B should be less than 4 ---, permute the correspondant x and $\epsilon from a vector to an other. That is :

BNB(B, NB, 1,2) gives

B=[ϵ0,x2,ϵ3,ϵ4] and NB=[x0,x1,ϵ1,x3]

By advance thanks for the help.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
0

answered 4 years ago

slelievre gravatar image

One solution is to define an exchange function as below.

The function starts by checking the validity of the indices.

If called with invalid indices, it will raise a value error.

def exchange(A, B, i, j):
    r"""
    Exchange entry ``i`` of ``A`` and entry ``j`` of ``B``.
    """
    if i not in range(len(A)):
        a = len(A)
        s = f"expected 0 <= i < len(A), got i = {i}, len(A) = {a}"
        raise ValueError(s)
    if j not in range(len(B)):
        b = len(B)
        s = f"expected 0 <= j < len(B), got j = {j}, len(B) = {b}"
        raise ValueError(s)
    A[i], B[j] = B[j], A[i]

To illustrate usage, define two vectors:

sage: A = vector(var('x', n=3, latex_name='x'))
sage: B = vector(var('y', n=4, latex_name='ϵ'))

and exchange some entries:

sage: exchange(A, B, 1, 2)
sage: A
(x0, y2, x2)
sage: B
(y0, y1, x1, y3)

Calling with invalid indices raises an error:

sage: exchange(A, B, 3, 3)
Traceback (most recent call last)
...
ValueError: expected 0 <= i < len(A), got i = 3, len(A) = 3
Preview: (hide)
link

Comments

Thanks a lot the core action is so simple that it is nearly unbelievable

Cyrille gravatar imageCyrille ( 4 years ago )

That's one of the benefits of having based Sage on the Python programming language!

slelievre gravatar imageslelievre ( 4 years ago )

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: 4 years ago

Seen: 715 times

Last updated: Aug 02 '20