我正在编写一个脚本来有效地解决数独难题,但我认为我的代码中有一部分非常丑陋并且想要简化。
def square(cell):
rows='ABCDEFGHI'
cols='123456789'
cell_row = cell[0][0]
cell_col = cell[0][1]
if cell_row in rows[0:3]:
x = 'A'
if cell_row in rows[3:6]:
x = 'B'
if cell_row in rows[6:9]:
x = 'C'
if cell_col in cols[0:3]:
y = 'a'
if cell_col in cols[3:6]:
y = 'b'
if cell_col in cols[6:9]:
y = 'c'
return (['Aa','Ab','Ac','Ba','Bb','Bc','Ca','Cb','Cc'].index(x+y))+1
鉴于数独棋盘由 9 个 3x3 正方形组成,此函数的目的是获取棋盘上某个单元格的坐标并返回该单元格所属的 3x3 正方形的编号(顶部的正方形左边是 1 号,右下是 9 号)。输入“单元格”的格式为 ['A5', 6],其中 A 表示行,5 表示列,6 表示单元格的值。
我的代码可以工作,但必须有一种更有效或更美观的方式来实现。如果有任何建议,我将不胜感激。
请您参考如下方法:
就我个人而言,我不认为像“65”和“97”这样的神奇数字可以使解决方案更表现!怎么样:
def square(cell):
rows = 'ABCDEFGHI'
cell_row = rows.index(cell[0][0])
cell_col = int(cell[0][1]) - 1
return 3 * (cell_row // 3) + cell_col // 3 + 1
