简体   繁体   中英

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?

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())
import random
print [random.sample(cities,n) for i in xrange(n)]

You can try this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM