Ask Your Question
0

How to permute strings from two lists (or vectors)

asked 2020-08-02 22:13:37 +0100

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=[\epsilon_0,x_2,\epsilon_3,\epsilon_4]$ and $NB=[x_0,x_1,\epsilon_1,x_3]$

By advance thanks for the help.

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
0

answered 2020-08-02 22:34:25 +0100

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
edit flag offensive delete link more

Comments

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

Cyrille gravatar imageCyrille ( 2020-08-03 09:15:41 +0100 )edit

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

slelievre gravatar imageslelievre ( 2020-08-03 14:39:38 +0100 )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

Stats

Asked: 2020-08-02 22:13:37 +0100

Seen: 545 times

Last updated: Aug 02 '20