yesthisisme
yesthisisme

Reputation: 21

Generating a list of random permutations of another list

So, I'm trying to tackle the TSP with a Genetic Algorithm. To do that I need to create a population pool. What I wan't to accomplish is to create a list of random permutations that will represent a population pool. I'm trying to do this using random.shuffle. Here's my code that should handle that part. Cities is a list of cities and routes is where I want to keep the population pool (a list of N random permutations):

for x in range(n):
    random.shuffle(cities)
    routes.append(cities)

What happens is that it just appends the same permutation n times. Anybody have any idea about what I might be missing?

Upvotes: -1

Views: 533

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46879

shuffle modifies the list in-place. you need to add a copy of the list to your routes; otherwise a reference to the same list is added which will be in its last shuffled state.

for x in range(n):
    random.shuffle(cities)
    routes.append(cities.copy())

Upvotes: 3

vks
vks

Reputation: 67968

import random
print [random.sample(cities,n) for i in xrange(n)]

You can try this.

Upvotes: 1

Related Questions