Python帮助:查找重复

2024-09-19 23:31:47 发布

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

我在下面的函数中把字母“b”放在矩阵中的某个位置。(我正在制造扫雷艇,这些“b”代表炸弹在矩阵中的位置)。我必须将“z”炸弹放入函数中,但炸弹放置的位置不能出现多次。我知道如何将它们放在函数中,但我不知道它们是否在重复

from random import*

mat1 = []
mat2 = []
def makemat(x):
    for y in range(x):
        list1 = []
        list2 = []
        for z in range(x):
            list1.append(0)
            list2.append("-")
        mat1.append(list1)
        mat2.append(list2)
makemat(2)

def printmat(mat):
    for a in range(len(mat)):
        for b in range(len(mat)):
            print(str(mat[a][b]) + "\t",end="")  
        print("\t")

def addmines(z):
    for a in range(z):
        x = randrange(0,len(mat1))
        y = randrange(0,len(mat1))   
        mat1[y][x] = "b"            
addmines(4)                         

谢谢


Tags: 函数inforlendefrange矩阵炸弹
2条回答

也许我不明白这个问题,但为什么不检查一下“b”是否已经存在呢?你知道吗

def addmines(z):
for a in range(z):
    x = randrange(0,len(mat1))
    y = randrange(0,len(mat1))
    if mat1[y][x] == "b":
        addmines(1)
    else:
        mat1[y][x] = "b"
addmines(4)

你要做的是不更换样品。尝试使用^{}

import random

...

def addmines(countMines):
    countRows = len(mat1)
    countCols = len(mat1[0])
    countCells = countRows * countCols

    indices = random.sample(range(countCells), countMines)

    rowColIndices = [(i // countRows, i % countRows) for i in indices]

    for rowIndex, colIndex in rowColIndices:
        mat1[rowIndex][colIndex] = 'b'

相关问题 更多 >