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可以这样学》被宝岛台湾的博硕文化股份有限公司(出版社)引入宝岛台湾发行繁体版。返回搜狐,查看更多

责任编辑:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值