A random Python sequence with a seed

Hi I am doing this for a school project (therefore I cannot use any additional functions) and I am using Python 2.6.6.

I have a list of numbers from 1 to 1000, and my seed will be, say, 448.

How can I create a random sequence with this seed so that the numbers in my list are in a different index?

And is it possible, knowing the seed, to return the elements in my list to their original position?

Sorry if this is confusing, but English is not my first language.

Thanks,

Favolas

+8
python random
source share
2 answers
import random SEED = 448 myList = [ 'list', 'elements', 'go', 'here' ] random.seed(SEED) random.shuffle(myList) print myList 

leads to

 ['here', 'go', 'list', 'elements'] 

Your list is now pseudo-authorized.

Pseudo is important because all lists that have the same seed and number of items are returned in the same "random" order. We can use this to not shuffle your list; if it were truly random, it would be impossible.

 Order = list(range(len(myList))) # Order is a list having the same number of items as myList, # where each position value equals its index random.seed(SEED) random.shuffle(Order) # Order is now shuffled in the same order as myList; # so each position value equals its original index originalList = [0]*len(myList) # empty list, but the right length for index,originalIndex in enumerate(Order): originalList[originalIndex] = myList[index] # copy each item back to its original index print originalList 

leads to

 ['list', 'elements', 'go', 'here'] 

TA-dah! originalList is now the initial order of myList.

+25
source share

A simple python document validation http://docs.python.org/library/random.html talks about

 random.seed([x]) 

which you can use to initialize the seed.

To get the elements again in the order of your initial value, set the seed again and get random numbers again. You can then use this index to retrieve the contents of the list, or simply use the index for anything.

You just sort the list and you will be sorted again.

+1
source share

Source: https://habr.com/ru/post/650534/


All Articles