How to permute a list of elements in sage

37 views
Skip to first unread message

jianrong

unread,
May 19, 2019, 11:29:21 PM5/19/19
to sage-support
Dear All,

I am trying to write a function in sage to permute a list of elements.

def f(i, v1):
v=[]
for j in v1:
v.append(j)

print(v)
v[i+1]=v1[i]
v[i]=v1[i+1]
return v

But the above codes do not work. I couldn't figure out the mistake. Thank you very much.

Justin C. Walker

unread,
May 19, 2019, 11:42:04 PM5/19/19
to SAGE Support
It would help to know what “codes do not work” means. Do you get an error message, or does the function f() not produce the result you want.

It may be that you do not have much experience with the Python programming language. There is extensive documentation available at <https://python.org>.

In case your copy of the code you are writing was exactly what you used, the problem may be that you are not following the indentation rules that Python uses. This code, which is the same as yours, except for indentation, works for me:

def f(i, v1):
v=[]
for j in v1:
v.append(j)
print(v)
v[i+1]=v1[i]
v[i]=v1[i+1]
return v

HTH

Justin

--
Justin C. Walker, Curmudgeon-At-Large
Institute for the Absorption of Federal Funds
--------
Men are from Earth.
Women are from Earth.
Deal with it.
--------



jianrong

unread,
May 20, 2019, 3:14:03 AM5/20/19
to sage-support
Thank you very much!

slelievre

unread,
May 20, 2019, 3:42:12 AM5/20/19
to sage-support
Simplifying the function and adding a docstring with an example:

def f(i, v1):
    r"""
    Return a copy of this list with elements of index `i` and `i + 1` swapped.

    EXAMPLE::

        sage: l = [5, 4, 3, 2, 1, 0]
        sage: f(3, l)
        [5, 4, 3, 1, 2, 0]
    """
    v = list(v1)
    v[i], v[i+1] = v[i+1], v[i]
    return v

Thanks to the docstring, one can now obtain the documentation
of the function with the usual question mark:

sage: f?

or the help function

sage: help(f)

Daniel Krenn

unread,
May 20, 2019, 3:44:48 AM5/20/19
to sage-s...@googlegroups.com
On 20.05.19 05:29, jianrong wrote:
> I am trying to write a function in sage to permute a list of elements.

An alternative might me something along the following:

|
Permutation("(1,2,3)(4,5)").action(['a', 'b', 'c', 'd', 'e'])
|
Reply all
Reply to author
Forward
0 new messages