Random Permutation

1,134 views
Skip to first unread message

Santanu Sarkar

unread,
Mar 5, 2011, 12:38:19 AM3/5/11
to sage-s...@googlegroups.com
How one can generate random permutation over the set
A={1,2,...,50}?

Mike Hansen

unread,
Mar 5, 2011, 12:40:46 AM3/5/11
to sage-s...@googlegroups.com

sage: Permutations(50).random_element()
[23, 40, 6, 27, 33, 43, 4, 34, 8, 39, 10, 35, 14, 41, 37, 21, 50, 44,
13, 46, 7, 16, 1, 2, 31, 38, 49, 36, 12, 28, 9, 5, 3, 19, 32, 48, 24,
26, 18, 22, 30, 45, 47, 11, 25, 17, 20, 29, 42, 15]

--Mike

Jason Grout

unread,
Mar 5, 2011, 12:42:21 AM3/5/11
to sage-s...@googlegroups.com
On 3/4/11 11:38 PM, Santanu Sarkar wrote:
> How one can generate random permutation over the set
> A={1,2,...,50}?
>


I think this does it:

sage: Permutations(50).random_element()
[11, 4, 30, 48, 49, 36, 22, 16, 27, 6, 44, 33, 13, 50, 9, 35, 15, 12,
26, 45, 1, 18, 2, 40, 19, 10, 28, 7, 37, 46, 25, 29, 34, 41, 38, 24, 8,
20, 32, 21, 14, 23, 31, 47, 43, 17, 3, 39, 5, 42]


Jason


Simon King

unread,
Mar 4, 2013, 7:38:29 AM3/4/13
to sage-s...@googlegroups.com
Hi Gary,

On 2013-03-04, GaryMak <garym...@googlemail.com> wrote:
>> sage: Permutations(50).random_element()
>> [11, 4, 30, 48, 49, 36, 22, 16, 27, 6, 44, 33, 13, 50, 9, 35, 15, 12,
>> 26, 45, 1, 18, 2, 40, 19, 10, 28, 7, 37, 46, 25, 29, 34, 41, 38, 24, 8,
>> 20, 32, 21, 14, 23, 31, 47, 43, 17, 3, 39, 5, 42]
>
> I have a set of size (say) 50 and I would like to generate a randomly-ordered list of its elements. The trouble is, if I
> use Permutations(my_set).random_element() it seems to want to generate the whole lot of them before picking out a random
> one!! Sorry but I cannot find how else to invoke this functionality, but I know there must be a better way ....

Permutations(50).random_element() is quite fast, and I think it does
*not* try to enumerate Sym(50).

I'd do:
sage: L = some list
sage: p = Permutations(len(L)).random_element()
sage: L_rand = [L[p[i]-1] for i in range(len(L))]

Note that it is p[i]-1, because addressing list elements in Python is
zero-based, but Permutations(50) permutes the numbers from 1 to 50, not
from 0 to 49.

Best regards,
Simon

Martin Albrecht

unread,
Mar 4, 2013, 8:10:39 AM3/4/13
to sage-s...@googlegroups.com
Why not use shuffle()?
Cheers,
Martin

--
name: Martin Albrecht
_pgp: http://pgp.mit.edu:11371/pks/lookup?op=get&search=0x8EF0DC99
_otr: 47F43D1A 5D68C36F 468BAEBA 640E8856 D7951CCF
_www: http://martinralbrecht.wordpress.com/
_jab: martinr...@jabber.ccc.de
Reply all
Reply to author
Forward
0 new messages