Python中的数独数独。局部变量问题

问题描述 投票:0回答:1

我正在尝试使我的电脑填写具有一些额外要求的数独。我将数独中的所有位置都分配给了这样的变量。 aa =“ 11”(aa在左上角),ii =“ 99”。我需要字符串而不是整数来处理我的难题的额外要求。

示例:

aa, ab, ac, ad, ae, af, ag, ah, ai = "11", "12", "13", "14", "15", "16", \
                                 "17", "18", "19"

此外,我也像这样制作了行和列:

row1 = [aa, ab, ac, ad, ae, af, ag, ah, ai]
row2 = [ba, bb, bc, bd, be, bf, bg, bh, bi]

rows = [row1, row2, etc...]

col1 = [row[0] for row in rows]
col2 = [row[1] for row in rows]

这是我应该填写的数独功能:

def sudoku():
    for var in alles:
        options = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
        for row in rows:
            if var in row:
                for other in row:
                    if other in options:
                        options.remove(other)
        for col in cols:
            if var in col:
                for other in col:
                    if other in options:
                        options.remove(other)

        if options != []:
            var = random.choice(options)
        else:
            break

想法是,它为数独的每个位置(同等变量)分配一个新值,并且该新值不能已经在同一行或同一列中。

问题是我的函数似乎根本没有改变'var'。此外,当将鼠标悬停在函数中的最后一个“ var”上时,pycharm会发出通知:“未使用局部变量”。

您知道如何使我的功能按预期工作吗?

感谢您的阅读,希望您有一个快乐,健康的2020年:)

python sudoku puzzle
1个回答
0
投票

有几个问题:

  • 主要问题是您希望对var的赋值会对您创建的列表产生影响。事实并非如此。即使您从var中检索了alles,但只要将新值分配给var,它就与alles无关。您应该分配给alles[i]之类的东西,其中要增加的索引是。更自然的是让两个索引从0变为8,并使用一个二维列表,您可以使用这两个索引进行访问。

  • 您将坐标存储在列表中。但这是非常无用的信息,因为您可以通过索引(从0到8)直接寻址列表中的任何值。您在行和列中的search确实是坐标,这是浪费时间。如果您正确设置列表,则可以直接指向当前所在的右行和右列。

这里是您怎么做的:

import random

rows = [
    [None] * 9, # no need to store coordinates. Just None is fine
    [None] * 9,
    [None] * 9,
    [None] * 9,
    [None] * 9,
    [None] * 9,
    [None] * 9,
    [None] * 9,
    [None] * 9
]

def sudoku(rows):
    for rownum in range(9):
        for colnum in range(9):
            options = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
            for other in rows[rownum]: # in the current row
                if other in options:
                    options.remove(other)
            # You can get the current values from the current column
            # and iterate those:
            for other in [row[colnum] for row in rows]:
                if other in options:
                    options.remove(other)
            if options == []:
                return
            # This assignment will work:
            rows[rownum][colnum] = random.choice(options)

sudoku(rows)

您会发现,这种蛮力方法将在处理第三行时退出,因为它无法再找到任何选项。因此,这不是解决数独的好方法。

© www.soinside.com 2019 - 2024. All rights reserved.