2022年 11月 14日

python自动出题_使用Python编写数独游戏自动出题程序

原标题:使用Python编写数独游戏自动出题程序

数独是一个很好玩的游戏,可以锻炼推理能力。下面的代码可以自动生成数独游戏题目。

fromrandom importshuffle, randrange

defgenerate():

# 初始网格

result = []

line = list(range(1,10))

fori inrange(9):

result.append(line)

line.append(line.pop(0))

# 注意,这里的切片很重要

line = line[:]

# Python允许函数的嵌套定义

defswitchRows(first, second):

# 这里的括号和换行不是必须的

# 只是为了方便手机阅读

(result[first],

result[second]) =

(result[second],

result[first])

defswitchColumns(first, second):

forindex inrange(9):

(result[index][first],

result[index][second]) =

(result[index][second],

result[index][first])

# 随机交换行

randomRows = list(range(9))

shuffle(randomRows)

fori inrange(0,7,2):

switchRows(randomRows[i],

randomRows[i+1])

# 随机交换列

randomColumns = list(range(9))

shuffle(randomColumns)

fori inrange(0,7,2):

switchColumns(randomColumns[i],

randomColumns[i+1])

# 随机清空一些格子

num = randrange(25, 50)

positions = {(randrange(9),randrange(9))

fori inrange(num)}

forrow, col inpositions:

result[row][col] = ‘ ‘

returnresult

defoutput(grids):

print(‘+’+’-+’*9)

forrow inrange(9):

line = ‘|’.join(map(str,grids[row]))

line = line.join([‘|’]*2)

print(line)

print(‘+’+’-+’*9)

grids = generate()

output(grids)

运行结果一:

运行结果二:

运行结果三:

———–我是分割线———-

———-我是分割线———–

热烈庆祝拙作《Python可以这样学》被宝岛台湾的博硕文化股份有限公司(出版社)引入宝岛台湾发行繁体版。返回搜狐,查看更多

责任编辑: