Python随机生成相同的矩阵

时间:2018-02-28 15:42:56

标签: python python-3.x

我有以下代码,当运行时生成相同的矩阵,但我希望它每次生成一个不同的矩阵。

我认为样本方法存在随机问题,但我不确定如何修复它。我也尝试创建一个随机对象并使用样本,但它具有相同的效果。

createIndividual函数的目的是获取给定的网格并用1-9的排列填充每一行,但是这些行带有一些不应重复的预定义值。这个功能有效。但是,当使用createPopulation函数多次调用它时,每次我希望每个矩阵都是唯一的时,它会返回相同的矩阵。

from random import sample

POPULATION_SIZE = 10

prefill = [[4,0,0,1,0,2,6,3,0],
           [5,0,0,6,4,3,8,0,0],
           [7,6,0,5,0,8,4,1,2],
           [6,0,0,0,0,9,3,4,8],
           [2,4,0,8,3,0,9,5,0],
           [8,0,9,4,1,5,0,7,0],
           [0,7,2,0,0,4,0,6,0],
           [0,5,4,2,0,0,0,8,9],
           [0,8,6,3,0,7,1,2,4]]

def createPopulation(grid):
    result = []
    for i in range(POPULATION_SIZE):
        result.append(createIndividual(grid))
    return result

def createIndividual(grid):
  '''
  Populates each row with random permuations from 1-9 avoiding duplicates.
  '''
  for i in range(len(grid)):
    permutation = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    temp = set()
    for j in range(len(grid)): # Remove pre existing
      if grid[i][j] != 0:
        permutation.remove(grid[i][j])
        temp.add(j)
    for j in range(len(grid)): # Randomly fill in blanks
      if grid[i][j] == 0:
        n = sample(permutation, 1)[0]
        permutation.remove(n)
        grid[i][j] = n

  return grid

pop = createPopulation(prefill)
for i in pop:
    print(i)

2 个答案:

答案 0 :(得分:4)

您的问题出在createIndividual函数中。它有副作用,即它修改原始的prefill矩阵。因此,在第一次运行中,它正确填充间隙并返回矩阵,但同时它会更改原始prefill。在所有后续调用中,它按原样返回prefixl,因为它不再有间隙......

答案 1 :(得分:1)

查看random.shuffle https://docs.python.org/2/library/random.html

它将随机重新排序列表,因为它是重新排序,所以您不会获得重复项。

prefill = [[4,0,0,1,0,2,6,3,0],
       [5,0,0,6,4,3,8,0,0],
       [7,6,0,5,0,8,4,1,2],
       [6,0,0,0,0,9,3,4,8],
       [2,4,0,8,3,0,9,5,0],
       [8,0,9,4,1,5,0,7,0],
       [0,7,2,0,0,4,0,6,0],
       [0,5,4,2,0,0,0,8,9],
       [0,8,6,3,0,7,1,2,4]]
for row in prefill:
  random.shuffle(row)

请注意,它会将它们混合到位,但每次创建一个新矩阵的功能如下:

def create_random_square_matrix(size):
  matrix = []
  values = range(1, size + 1)
  for i in range(size):
    row = list(values)
    random.shuffle(row)
    matrix.append(row)
  return matrix

nine_by_nine = create_random_square_matrix(9)