0
# N-Queens Problem
import random

# Define size of board
SIZE_OF_BOARD = 8
POPULATION_SIZE = 50

population = []

startingIndividual = []
# Populate starting individual
for x in range(0, SIZE_OF_BOARD):
    startingIndividual.append(x)

for x in range(0, POPULATION_SIZE - 1):
    population.append(startingIndividual)

for x in population:
    random.seed()
    random.shuffle(x)

print(population)

So, when I run this program I get the same permutation 50 times. Even though I reseed shuffle for each list I am shuffling, the result is still the same. Where exactly am I going wrong?

Ian Trapp
  • 11
  • 4
  • Your `population` list contains 50 references to the *same* list. Replace `population.append(startingIndividual)` with `population.append(startingIndividual[:])`, and remove the `random.seed()` call inside the loop. (Or if you're on Python 3, you might want to write that line as `population.append(startingIndividual.copy())`.) – Mark Dickinson Sep 18 '16 at 13:59
  • @MarkDickinson that was it. Such a simple fix, I really appreciate it. – Ian Trapp Sep 18 '16 at 14:07
  • Also note: There is no need to call `seed` more than once (and in other languages, or when passing an explicit seed value in Python, it would *cause* the problem you're trying to avoid). – ShadowRanger Sep 18 '16 at 14:21
  • @ShadowRanger There is no need to call `seed()` at all. – John Coleman Sep 18 '16 at 16:33
  • @JohnColeman: Agreed, though I understand the impulse to do so, given the problems with not doing so with stuff like C's `rand`. – ShadowRanger Sep 18 '16 at 21:55

0 Answers0