数独是一个很好玩的游戏,可以锻炼推理能力。下面的代码可以自动生成数独游戏题目。
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)
grids = generate() output(grids)
运行结果一:
运行结果二:
运行结果三: