从中当前未显示的范围生成随机整数

2024-09-30 16:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用python做数独,我想随机填充一个有空格的行。你知道吗

<> >我有一个函数来检测空白位置,还有一个函数来生成int来填充。你知道吗

比如说,如果一行是[1 , 2 , ?, ?] 当position函数命中第一个'?'时,random函数应该提供3或4的选择。然后是3,位置函数打第二个'?',随机函数应该只提供'4'的选择。你知道吗

问题是我的结果是错误的:例如,-1表示空格:

[[-1 -1  3  4]
 [ 3 -1 -1 -1]
 [ 2  3 -1 -1]
 [-1 -1 -1 -1]]

[[1 4 3 4]
 [3 4 1 1]
 [2 3 4 3]
 [3 1 4 2]]

零件代码为:

self.F1 = np.where(self.oriMatrix == -1)

def randgit(self, row):
    while True:
        digit = randint(1, self.shape)
        for col in range(0, self.shape):
            if digit == self.pMatrix[row,col]:
                break
        return digit

def randFill(self):
    for mark in range(0, self.F1[0].size):
        pos = [self.F1[0][mark], self.F1[1][mark]]
        self.pMatrix[pos[0], pos[1]] = self.randgit(pos[0])

pMatrix这是4x4矩阵,有人能找出我的错误还是有更好的方法?你知道吗


Tags: 函数posselffordef错误colrow
1条回答
网友
1楼 · 发布于 2024-09-30 16:28:27

你的描述和不完整的代码很难说清楚你的问题是什么。你知道吗

我猜你在问:

We're given a row r that has n elements in it.

For each element in r equal to -1, fill it with a value x, that is:

  1. In the range of 1 <= x <= n, and
  2. Not already used in the row

如果这是对你的问题的适当重申,请考虑以下内容:

import numpy as np
import random

m = np.array([
    [-1, -1,  3,  4],
    [ 3, -1, -1, -1],
    [ 2,  3, -1, -1],
    [-1, -1, -1, -1]])

for (i,r) in enumerate(m):
    all_values = set([(x+1) for x in range(len(r))])    # All possible values in [1,n]
    tak_values = set(r)                                 # "Taken" values already in r
    tak_values.discard(-1)                              # Discard -1 from the set
    rem_values = all_values - tak_values                # "Remaining" values, from
    print("Row %d" % i)                                 #   which to choose x
    print("  Remaining  values: %s" % rem_values)
    print("  Random choice: %d" % random.choice(list(rem_values)))

对我来说,刚刚印出来的是:

Row 0
  Remaining  values: set([1, 2])
  Random choice: 1
Row 1
  Remaining  values: set([1, 2, 4])
  Random choice: 2
Row 2
  Remaining  values: set([1, 4])
  Random choice: 4
Row 3
  Remaining  values: set([1, 2, 3, 4])
  Random choice: 1

我试着在上面的代码中“慢行”,这样你就可以很容易地检查不同的变量是什么,等等。当然,有了很多这样的答案,我们可能会大大缩短它。你知道吗

相关问题 更多 >