# How to permute strings from two lists (or vectors)

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 close merge delete

Sort by » oldest newest most voted

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

more

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

( 2020-08-03 09:15:41 +0200 )edit

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

( 2020-08-03 14:39:38 +0200 )edit