Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python shuffling with a parameter to get the same result

Tags:

python

import random x = [1, 2, 3, 4, 5, 6] random.shuffle(x) print x 

I know how to shuffle a list, but is it possible to shuffle it with a parameter such that the shuffling produces the same result every time?

Something like;

random.shuffle(x,parameter) 

and the result is the same for this parameter. Say parameter is 4 and the result is [4, 2, 1, 6, 3, 5] every time.

like image 823
Co Koder Avatar asked Oct 10 '13 21:10

Co Koder


People also ask

How do you shuffle output in Python?

In Python, you can shuffle (= randomize) a list, string, and tuple with random. shuffle() and random. sample() . random.

What does shuffle () do in Python?

The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.

How do you shuffle a range of numbers in Python?

You can use range() along with list() to generate a list of integers, and then apply random. shuffle() on that list.

How do you randomly shuffle a list with seeds in Python?

Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.


1 Answers

As the documentation explains:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

So, you can just create your own random.Random instance, with its own seed, which will not affect the global functions at all:

>>> import random >>> x = [1, 2, 3, 4, 5, 6] >>> random.Random(4).shuffle(x) >>> x [4, 6, 5, 1, 3, 2] >>> x = [1, 2, 3, 4, 5, 6] >>> random.Random(4).shuffle(x) >>> x [4, 6, 5, 1, 3, 2] 

(You can also keep around the Random instance and re-seed it instead of creating new ones over and over; there's not too much difference.)

like image 65
abarnert Avatar answered Sep 22 '22 17:09

abarnert