用python显示2D数独板

我想用python显示一个2D数独板,如下所示:

0 0 3 |0 2 0 |6 0 0 
9 0 0 |3 0 5 |0 0 1 
0 0 1 |8 0 6 |4 0 0 
------+------+------
0 0 8 |1 0 2 |9 0 0 
7 0 0 |0 0 0 |0 0 8 
0 0 6 |7 0 8 |2 0 0 
------+------+------
0 0 2 |6 0 9 |5 0 0 
8 0 0 |2 0 3 |0 0 9 
0 0 5 |0 1 0 |3 0 0

我用这个代码在没有分隔线的情况下显示了电路板:

^{pr2}$

values是一个字典{'A1':'0','A2':'0','A3':'3','A4':'0','A5':'2'…等等。}我得到这个输出:

0 0 3 0 2 0 6 0 0
9 0 0 3 0 5 0 0 1
0 0 1 8 0 6 4 0 0
0 0 8 1 0 2 9 0 0
7 0 0 0 0 0 0 0 8
0 0 6 7 0 8 2 0 0
0 0 2 6 0 9 5 0 0
8 0 0 2 0 3 0 0 9
0 0 5 0 1 0 3 0 0

这是一个有点混乱的方法。如果在行和列字符串中添加其他标识符,则实际上会以可识别的形式获取列之间的中间值:

# Use "x" as an identifier for a row or column where there should be a separator
rows = 'ABCxDEFxGHI'
cols = '123x456x789'

values = {'A1': '0', 'A2': '0', 'A3': '3'}
def display(values):
    for r in rows:
        for c in cols:
            if r == "x":
                if c == "x":
                    # Both row and column are the separator, show a plus
                    print "+",
                else:
                    # Only the row is the separator, show a dash
                    print "-"
            elif c == "x":
                    # Only the column is the separator, show a pipe
                print "|",
            else:
                # Not a separator, print the given cell (or ? if not found)
                print values.get(r+c, "?"),
        # Make sure there's a newline so we start a new row
        print ""

display(values)

另一种可能是更聪明地将经过分隔符修改的单元格插入字典(即"xx": "+", "Ax": "|"),但这需要更多的工作。但是,您可以使用字典的get()方法自动填充其中的一组(即默认返回管道或连字符)。

下面的方法可能有用。但我认为,一个将字符串作为结果呈现的函数可能更有用(例如,对于将结果写入文本文件,而不需要太多的monkey补丁)。在

rows = 'ABCDEFGHI'
cols = '123456789'

def display(values):
    for i, r in enumerate(rows):
        if i in [3, 6]:
            print '------+-------+------'
        for j, c in enumerate(cols):
            if j in [3, 6]:
                print '|',
            print values[r + c],
        print

结果:

^{pr2}$

猜你喜欢

转载自blog.csdn.net/babyai996/article/details/131986970
2D