检查Python中的类型
我目前正在学习我的第一门Python课程,并得到了以下练习:检查Python中的类型,python,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,
# 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
我的想法是通过以下方式解决这个问题:
type('a') is str
或
据我所知,如果输入包含一个不是整数的元素,你可以确定它不是一个有效的数独方块。因此,您不需要进行类型检查:
def isValidSudokuSquare(inp):
try:
# .. validation that assumes elements are integers
except TypeError:
return False
(旁白/提示:如果您使用Python,您可以在大约两行非常可读的代码中实现此验证的其余部分。)如果项是字符串,您可以使用
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")
但正确答案和错误答案的例子清楚地证明了这些元素是数字的,我不明白你的意思。incorrect4是由字符串组成的,所以我不能使用索引来遍历列表。好的,但是如果平方包含任何非整数的值,它是无效的,对吗?那么,异常处理?啊,是的,你是对的。不过,出于实践的考虑,最好包括值不是整数的情况。我还没有做任何异常处理。我来自C语言,所以我认为检查一个元素是否是字符串会很简单,如果是的话,把它转换成ASCII。在
type('a')is str
和isinstance('a',str)
之间有很大的区别。。。如果你打算将两者都作为一种解决方案,那么最好解释一下……谁能告诉我为什么这根本不改变str值:def check_数独(sudoku):对于数独中的e:对于e中的e:If type(e)==str:e=ord(e)返回sudoku@user2252633-不要重复使用变量:用于数独中的item:if…
@MattDMo这是真的,但我不知道它与我的答案有什么关系。这里的问题是关于转换类型。负整数是int,所以解决这个问题超出了范围
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")
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