Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python random sequence with seed

Tags:

python

random

I'm doing this for a school project (so I can't use any advanced features) and I'm using Python 2.6.6.

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

How can I generate a random sequence with that seed so that the numbers in my list will be in a different index?

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

Sorry if my question is confusing but English is not my native language.

Thanks.

like image 598
Favolas Avatar asked Dec 29 '10 20:12

Favolas


People also ask

What does random seed in python do?

random. seed(a, version) in python is used to initialize the pseudo-random number generator (PRNG). PRNG is algorithm that generates sequence of numbers approximating the properties of random numbers. These random numbers can be reproduced using the seed value.

How does seed work in random?

A random seed is a starting point in generating random numbers. A random seed specifies the start point when a computer generates a random number sequence. This can be any number, but it usually comes from seconds on a computer system's clock (Henkemans & Lee, 2001).

What is NP random seed in Python?

The numpy random seed is a numerical value that generates a new set or repeats pseudo-random numbers. The value in the numpy random seed saves the state of randomness. If we call the seed function using value 1 multiple times, the computer displays the same random numbers.


1 Answers

import random
SEED = 448

myList = [ 'list', 'elements', 'go', 'here' ]
random.seed(SEED)
random.shuffle(myList)

print myList

results in

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

Your list is now pseudorandomized.

'Pseudo' is important, because all lists having the same seed and number of items will return in the same 'random' order. We can use this to un-shuffle your list; if it were truly random, this would be impossible.

Order = list(range(len(myList)))
# Order is a list having the same number of items as myList,
# where each position's value equals its index

random.seed(SEED)
random.shuffle(Order)
# Order is now shuffled in the same order as myList;
# so each position's 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

results in

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

Tada! originalList is now the original ordering of myList.

like image 75
Hugh Bothwell Avatar answered Oct 01 '22 18:10

Hugh Bothwell