【问题标题】:variables that I only define and they change their values as the program progresses?我只定义的变量,它们随着程序的进行而改变它们的值?
【发布时间】:2018-08-05 05:56:46
【问题描述】:

我正在尝试构建数独求解器。要检查板子是否已解决,我需要所有行、列和框的总和。这就是我正在做的。

class puzzle():
    def __init__(self,puzzle):
        self.board = puzzle[:]    ## puzzle is of the form [[(row1)],[(row2)],[(row3)],...,[(row9)]]

        self.sumr1 = sum(i for i in self.board[0])
        ## and the sums of the other rows.
        ## Similar for columns and boxes.

但这只会使变量具有董事会最初给它们的值。每当我找到一个数字并将其放在它的位置时,我都不想手动更新它们的值。

我正在寻找诸如字典中的视图对象之类的东西。它们无需人工干预即可实时更新。请指导我。

【问题讨论】:

  • 你必须编写一个计算总和的函数,并在每次移动后调用它。
  • @DYZ 这就是我想要避免的。
  • 这是不可避免的。
  • @DYZ 好的。我想我会做一个功能来更新它们。谢谢。

标签: python variables


【解决方案1】:

您将需要检查谜题是否已解决,并使用返回的值来决定要做什么:

您必须检查行、列和 9 个 3x3 块;我认为行的总和不够

class puzzle():
    def __init__(self, puzzle):
        self.board = [row[:] for row in puzzle]    

    def is_solved(self)-> bool:
        compare_to = list(range(10))
        is_solved = True
        for row in self.board:
            is_solved = is_solved  and (sorted(row) == compare_to)
            if not is_solved:
                return False
        for idx in range(10):
            column = [row[idx] for row in self.board]
            is_solved = is_solved and (sorted(column) == compare_to)
            if not is_solved:
                return False

        # check the blocks here

        return is_solved

【讨论】:

    猜你喜欢
    • 2012-03-14
    • 2022-08-17
    • 1970-01-01
    • 2012-09-13
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    相关资源
    最近更新 更多