【发布时间】:2017-08-12 22:22:37
【问题描述】:
我目前正在复习考试,有教授给出的试卷。 问题涉及游戏 Sodoku;在本节中,我必须将一行值的所有非零值作为一个集合返回到数独表(由二维数组表示)中。
def get_values_from_row(puzzle, row):
rowVal = []
try:
for i in puzzle[row]:
if i != 0:
rowVal.append(i)
except IndexError:
print('Invalid Row')
if len(rowVal) == 0:
return rowVal
else:
rowVal = set(rowVal)
print(rowVal)
return(rowVal)
这里是数独板
sudoku1 = [[5, 3, 4, 6, 7, 8, 9, 1, 2],
[6, 7, 2, 1, 9, 5, 3, 4, 8],
[1, 9, 8, 3, 4, 2, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 9, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]]
当我为第 0 行运行函数时,我得到了预期的 {1,2,3,4,5,6,7,8,9}。但是,当我运行测试脚本时返回失败。
这是测试脚本中的相关代码:
import unittest
class Test(unittest.TestCase):
def test_get_values_from_row(self):
sudoku1 = [
[5, 3, 4, 0, 7, 8, 9, 1, 2],
[6, 7, 0, 0, 9, 5, 0, 4, 8],
[1, 9, 8, 0, 4, 0, 5, 6, 7],
[8, 5, 9, 7, 6, 1, 4, 2, 3],
[4, 2, 6, 8, 5, 3, 7, 9, 1],
[7, 1, 3, 0, 2, 4, 8, 5, 6],
[9, 6, 1, 5, 3, 7, 2, 8, 4],
[2, 8, 7, 4, 1, 9, 6, 3, 5],
[3, 4, 5, 2, 8, 6, 1, 7, 9]]
self.assertEqual(sg.get_values_from_row(sudoku1, 0), set([6]))
sg 正是我正在编辑的脚本导入的内容。当我查看日志时,显然6 不在集合中,当我将其更改为3 时,同样的事情发生了。看起来无论测试值是什么,它都会从我返回的列表中删除
Traceback (most recent call last):'
File "question_1_iii_test.py", line 23, in test_get_values_from_row'
self.assertEqual(sg.get_values_from_row(sudoku1, 0), set([6]))'
AssertionError: Items in the first set but not the second:'
1
2
3
4
5
7
8
9
Items in the second set but not the first:
6
我的问题是: 为什么 AssertEqual 明显为真时返回假?
【问题讨论】:
-
我认为你的逻辑是倒退的,你实际上是在问
{1, 2, 3, 4, 5, 7, 8, 9} == {6},显然是False。你想检查集合是不相交的吗?或者你想知道它是否是一个子集? -
好吧,我没有写测试脚本;这就是我不明白 AssertEqual 到底想做什么的问题;如果它说
{1, 2, 3, 4, 5, 7, 8, 9} == {6},那么测试脚本一定有问题吧?因为当问题要求返回一整套值而不仅仅是一个值时,那会测试什么 -
您确定
get_values_from_row()应该返回使用的值而不是未使用的值吗 - 测试似乎暗示它应该返回未使用的值。 -
The function should return a list (as a set built-in type) containing all non-zero values in that row, an empty list if the row is empty (i.e. contains only zeros).是准确的措辞
标签: python unit-testing equality sudoku