1

我目前正在学习我的第一门 Python 课程并进行了以下练习:

# THREE GOLD STARS

# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.

# Define a procedure, check_sudoku,
# that takes as input a square list
# of lists representing an n x n
# sudoku puzzle solution and returns the boolean
# True if the input is a valid
# sudoku square and returns the boolean False
# otherwise.

# A valid sudoku square satisfies these
# two properties:

#   1. Each column of the square contains
#       each of the whole numbers from 1 to n exactly once.

#   2. Each row of the square contains each
#       of the whole numbers from 1 to n exactly once.

# You may assume the the input is square and contains at
# least one row and column.

correct = [[1,2,3],
           [2,3,1],
           [3,1,2]]

incorrect = [[1,2,3,4],
             [2,3,1,3],
             [3,1,2,3],
             [4,4,4,4]]

incorrect2 = [[1,2,3,4],
             [2,3,1,4],
             [4,1,2,3],
             [3,4,1,2]]

incorrect3 = [[1,2,3,4,5],
              [2,3,1,5,6],
              [4,5,2,1,3],
              [3,4,5,2,1],
              [5,6,4,3,2]]

incorrect4 = [['a','b','c'],
              ['b','c','a'],
              ['c','a','b']]

incorrect5 = [ [1, 1.5],
               [1.5, 1]]

def check_sudoku():


#print check_sudoku(incorrect)
#>>> False

#print check_sudoku(correct)
#>>> True

#print check_sudoku(incorrect2)
#>>> False

#print check_sudoku(incorrect3)
#>>> False

#print check_sudoku(incorrect4)
#>>> False

#print check_sudoku(incorrect5)
#>>> False

我的想法是通过执行以下操作来解决此问题:

  1. 首先,我需要将所有列附加到列表中
  2. 然后我可以创建一个索引,并检查数独中的每个元素是否嵌套for循环if soduko.count(index) != 1 --> return false

但是,一个数独是由字符串中的字母组成的。我不知道该怎么办。在 a = 97 的情况下,我可以使用 ord() 将列表中的每个元素转换为 ASCII 并从 ASCII 代码开始索引。但这会给数字带来错误。所以在此之前我必须检查一个列表是数字还是字符串。我怎样才能做到这一点?

谢谢!

4

4 回答 4

1

您可以使用

type('a') is str

或者

isinstance('a', str)
于 2013-10-13T16:23:15.103 回答
1

据我了解,如果输入包含一个不是整数的元素,则可以确定它不是有效的数独方块。所以你不需要类型检查:

def isValidSudokuSquare(inp):
  try:
    # .. validation that assumes elements are integers
  except TypeError:
    return False

(旁白/提示:如果您使用sets ,您可以在大约两行非常易读的 Python 行中实现此验证的其余部分。)

于 2013-10-13T16:29:29.907 回答
1

如果项目是字符串,则可以使用isdigit()andisalpha()方法。你必须验证它们是字符串,否则你会得到一个异常:

if all([isinstance(x, int) for x in my_list]):
    # All items are ints
elif all([isinstance(x, str) for x in my_list]):
    if all([x.isdigit() for x in my_list]):
        # all items are numerical strings
    elif all([x.isalpha() for x in my_list]):
        # all items are letters' strings (or characters, no digits)
    else:
        raise TypeError("type mismatch in item list")
else:
    raise TypeError("items must be of type int or str")
于 2013-10-13T16:30:09.273 回答
0
def check_sudoku( grid ):
    '''
    list of lists -> boolean

    Return True for a valid sudoku square and False otherwise.
    '''

    for row in grid:        
        for elem in row:
            if type(elem) is not int:
                return False # as we are only interested in wholes 
            # continue with your solution
于 2013-10-13T17:32:38.150 回答