I am trying to write a genetic algorithm for homework to solve the travelling salesman problem.
One of the mutation functions that I'm trying is to use random.shuffle
on the tour.
When I read the documentation for random.shuffle
, I see:
shuffle(self, x, random=None, int=<type 'int'>) method of random.Random instance
x, random=random.random -> shuffle list x in place; return None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
Could someone please explain the function of the "random" parameter in this function? I have read this question, but it doesn't answer my question.
I would especially like to use this function if I can somehow control how random the shuffling would be (if that makes any sense)
The random
argument is used for specifying (another) random number generator. it's a function expected to return uniform random numbers in the range 0<=x<1
If the same number is returned twice from the random number generator, the shuffle will be the same. For example,
def mynonrandom():
return 0.1
q
[1, 2, 3, 4]
random.shuffle(q, mynonrandom)
q
[2, 3, 4, 1]
random.shuffle(q, mynonrandom)
q
[3, 4, 1, 2]
note that in this particular case I got a shift of -1 each time. Exactly what you get for a random input may depend on the implementation of random.shuffle.
For a genetic algorithm you want to be able to have variable sized randomness of the shuffle. That is not done with random.shuffle. You probably need to define some example changes (pairs with distance N swapping for example) and then randomize (with some parameters you'll define) how many of those operations you perform for each new set of genes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With