Python - 简化数独求解器代码

标签 python performance grid coordinates sudoku

我正在编写一个脚本来有效地解决数独难题,但我认为我的代码的一部分非常丑陋,想要简化。

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)。输入“cell”的格式为 ['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

关于Python - 简化数独求解器代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37710233/

相关文章:

extjs - 为网格制作良好的分页 - extJS

python - 如何使用 Pydantic 将此数据结构转换为 JSON?

Python:动态处理大文档的行

python - 使用 lxml 解析 HTML - 如何在结果列表中保留空内容?

android - 安卓中的图像?

c# - 在高负载系统 C# 中映射 POCO 的成本

css - LESS work around,网格系统,box-sizing

python - 在哪里可以了解 scrapy SgmlLinkExtractor?

python - 忽略指定值的 numpy 数组的平均值

grid - 使用 grid.arrange 为使用 gridExtra::grid.arrange 制作的多个图添加标题