检查Python中的类型

时间:2013-10-13 16:18:02

标签: python

我目前正在进行我的第一个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
  3. 但是,一个数独由字符串中的字母组成。我无法弄清楚该怎么做。我可以使用ord()将列表中的每个元素转换为ASCII,并在a = 97的情况下从ASCII代码开始索引。但这会给数字带来错误。所以在此之前我必须检查列表是数字还是字符串。我怎么能这样做?

    谢谢!

4 个答案:

答案 0 :(得分:1)

您可以使用

type('a') is str

isinstance('a', str)

答案 1 :(得分:1)

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

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

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

答案 2 :(得分:1)

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

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")

答案 3 :(得分: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