8. (实践题, 16.7分) 对一下python代码执行以下操作: def linear_searching(list, size, target): ① for i in range(0, size): ② if (list[i] == target): ③ return i ④ return -1 1 根据源代码画出控制流图 (提交截图) 2 计算环路复杂性 3 给出独立路径 4 给出测试数据 5 跟据第四步测试数据使用unittest框架对线性查找函数进行单元测试的代码。 要求:有相关包的导入 使用ddt驱动
时间: 2024-02-14 17:24:09 浏览: 106
1. 控制流图如下:
![linear_searching控制流图](https://i.imgur.com/b9yL7gP.png)
2. 环路复杂性:P = E - N + 2 = 8 - 7 + 2 = 3
3. 独立路径如下:
- 1-2-4
- 1-2-3-4
- 1-5-6-4
- 1-5-7-8-6-4
4. 测试数据:
```python
import unittest
from ddt import ddt, data, unpack
@ddt
class TestLinearSearch(unittest.TestCase):
@data(
([1, 2, 3, 4, 5], 5, 3, 2),
([1, 2, 3, 4, 5], 5, 6, -1),
([], 0, 1, -1),
([3], 1, 3, 0),
(["a", "b", "c"], 3, "b", 1)
)
@unpack
def test_linear_search(self, test_list, size, target, expected):
self.assertEqual(linear_search(test_list, size, target), expected)
if __name__ == '__main__':
unittest.main()
```
5. 完整代码如下:
```python
def linear_search(list, size, target):
for i in range(0, size):
if (list[i] == target):
return i
return -1
import unittest
from ddt import ddt, data, unpack
@ddt
class TestLinearSearch(unittest.TestCase):
@data(
([1, 2, 3, 4, 5], 5, 3, 2),
([1, 2, 3, 4, 5], 5, 6, -1),
([], 0, 1, -1),
([3], 1, 3, 0),
(["a", "b", "c"], 3, "b", 1)
)
@unpack
def test_linear_search(self, test_list, size, target, expected):
self.assertEqual(linear_search(test_list, size, target), expected)
if __name__ == '__main__':
unittest.main()
```
阅读全文