如何将if语句写入python代码,接下来列出哪些规则。代码必须检查是否任何5x5矩阵是宾果游戏。这是我的代码:
#Rules are simple
table=[[12,17,34,48,70], #first column integers are allowed 1-15
[14,25,40,56,61], #second column integers are allowed 16-30
[6,30,43,46,72], #third column integers are allowed 31-45
[12,16,42,63,65], #fourth column integers are allowed 46-60
[4,31,34,49,67]] #fifth column integers are allowed 61-75
def is_right_matrix(table):
for i in range(len(table)):
for j in range(len(table[i])):
if
return False
return True
答案 0 :(得分:0)
(我希望我能正确理解你的问题。)
您可以查看所有数字并检查是否存在范围内(特定于每列)。如果没有,则返回False。
这个(不那么漂亮)示例适用于NumPy数组以及“嵌套”列表(如表示例中的那个)
table=[[12,17,34,48,70],
[14,25,40,56,61],
[6,30,43,46,72],
[12,16,42,63,65],
[4,31,34,49,67]]
def is_valid_matrix(table):
for i, col in enumerate(table):
# i is the index of the column
# (so we know to which column each number belongs)
# col is the current column
# if the current column is the first column (indexes start at 0),
# check for numbers from 1 to 15:
if i == 0:
for n in col: # go through every number in that column
# check if that number is not in the range 1 to 15
# (range includes the first argument, but excludes the second)
if n not in range(1, 16):
# if so, immediately return False
# (and therefore exit out of the function)
return False
# if the current column is the second column,
# check for numbers from 16 to 30:
elif i == 1:
for n in col:
# check if that number is not in the range 16 to 31
if n not in range(16, 31):
return False
# and so on
elif i == 2:
for n in col:
if n not in range(31, 46):
return False
elif i == 3:
for n in col:
if n not in range(46, 61):
return False
elif i == 4:
for n in col:
if n not in range(61, 76):
return False
return True # if all "checks" passed/every number was valid: return True
答案 1 :(得分:0)
这是一个过于复杂的解决方案,但它包含额外的唯一性测试(宾果表中不允许重复)。
def is_valid(matrix):
floor = range(1, 62, 15)
ceiling = range(15, 76, 15)
i = 0
while i < len(floor):
for low, high in zip(floor, ceiling):
for j in list(range(len(matrix)):
if high < matrix[j][i] < low:
return False
i += 1
flat = sum(matrix, [])
if len(set(flat) != len(flat):
return False
return True