0

这是代码:

def row_check(table):
    for ealst in table:
            first = [ealst[0]]
            for each in ealst[1:]:
                    if each not in first:
                            first.append(each)
                    else:
                            return False
    return True

def col_check(table):
    col = []
    totalcol = []
    count = 0
    for rows in table:
            for columns in range(len(table)):
                    col.append(table[int(columns)][count])
            count += 1
            totalcol.append(col)
            col = []
    return totalcol

def check_sudoku(table):
    if row_check(table) and row_check(col_check(table)):
            return True
    return False

if __name__ == '__main__':
    table = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]
    check_sudoku(table)

这不是返回值 True。现在,当我在代码运行后手动调用该函数时,它会返回预期值:

>>> table
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> check_sudoku(table)
True

这是一个展示相同行为的最小示例:

def check_sudoku(table):
    return True

if __name__ == '__main__':
    table = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]
    check_sudoku(table)

为什么会发生这种情况,我该如何防止这种情况发生,即在调用时返回 True ?

4

1 回答 1

10
if __name__ == '__main__':
    table = [[1, 2, 3],
             [4, 5, 6],
             [7, 8, 9]]
    print check_sudoku(table) #you need to actually print stuff when running in a script 

它仅在您在 shell 中时打印返回值。当您运行脚本时,您必须实际打印您想要打印的任何内容......

于 2013-08-21T17:59:05.780 回答