So I have a list of 4 strings in Python and I want to return that list, but randomized and only up to a specific number (the variable ‘players’ in the code below). I CANNOT use the shuffle function, but trust me if I could, I would.
Here is the code I have so far:
players = raw_input('How many players? ')
players = int(players)
Roles = ["Role1", "Role2", "Role3", "Role4"]
print Roles[:players]
I need to somehow use the random.seed() function to randomize the list. I’m really confused by this, because I thought you could only use random.seed() with numbers, not a list of strings. If anyone could help with this I would really appreciate it.
While
random.shuffle(orrandom.sample) is The Python Way, consider using an existing well-known approach if it is truly not an option. The code below is an implementation of the Fisher-Yates Shuffle (it is adapted from the Sattolo’s variant code found on that page):Another approach that is sometimes seen floating about is to zip a list with a sequence of random numbers, sort based on the random numbers, and then extract the original values.
In any case,
random.seedmerely sets the seed for the PRNG (Pseudo-random number generator) used. That is,random.seedwill affect future random numbers generated (and functions which utilize them), but will not itself “get” a random value or “shuffle” or “randomize” anything. (It is usually fine if it is not called, as there is a suitable “default seed” set, but sometimes it’s nice – e.g. for repeatability in tests or Solitaire games – to set a particular seed.)For instance, try this: (If using Python 2.x, remove the parenthesis from the
print):The key to understand is a PSEUDO RANDOM source (PRNG) takes the CURRENT internal state – which can be set with a “seed”, although a modern PRNG has a much larger internal state – and uses that to generate a random value and the NEXT internal state. A TRUE RANDOM source (e.g. specialty hardware that samples static noise) does not have the concept of a “seed”.
Happy coding.