专栏名称: Python小屋
清华出版社《Python程序设计》系列教材作者董付国的Python小屋。介绍Python基础语法知识、标准库、扩展库知识,探讨Python在各领域的应用。
目录
相关文章推荐
Python开发者  ·  成人玩偶 + ... ·  2 天前  
Python爱好者社区  ·  DeepSeek彻底爆了! ·  2 天前  
Python爱好者社区  ·  DeepSeek 被放弃了,阿里牛逼! ·  昨天  
Python爱好者社区  ·  付费上班终于成为了现实。 ·  昨天  
Python开发者  ·  马斯克 20 万 GPU ... ·  3 天前  
51好读  ›  专栏  ›  Python小屋

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

Python小屋  · 公众号  · Python  · 2017-08-01 22:53

正文

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

from random import shuffle, randrange


def generate ():
# 初始网格
result = []
line = list ( range (1,10))
for i in range (9):
result.append(line)
line.append(line.pop(0))
# 注意,这里的切片很重要
line = line[:]


# Python允许函数的嵌套定义
def switchRows (first, second):
# 这里的括号和换行不是必须的
# 只是为了方便手机阅读

(result[first],
result[second]) =\
(result[second],
result[first])


def switchColumns (first, second):
for index in range (9):
(result[index][first],
result[index][second]) =\
(result[index][second],
result[index][first])


# 随机交换行
randomRows = list ( range (9))
shuffle(randomRows)
for i in range (0,7,2):
switchRows(randomRows[i],\
randomRows[i+1])

# 随机交换列
randomColumns = list ( range (9))
shuffle(randomColumns)
for i in range (0,7,2):
switchColumns(randomColumns[i],\
randomColumns[i+1])

# 随机清空一些格子

num = randrange(25, 50)
positions = {(randrange(9),randrange(9))\
for i in range (num)}
for row, col in positions:
result[row][col] = ' '


return result


def output (grids):
print ( '+' + '-+' *9)
for row in range (9):
line = '|' .join( map ( str ,grids[row]))
line = line.join([ '|' ]*2)
print (line)
print ( '+' + '-+' *9)








请到「今天看啥」查看全文