下面给出了python代码(q4.py):
#!/usr/bin/env python
def DFS(j, visited, zombies, row):
for k in range(row):
if zombies[j][k] == '1' and visited[j][k] == False and visited[k][j] == False:
visited[j][k] = True
visited[k][j] = True
DFS(k, visited, zombies, row)
def zombieCluster(zombies):
row = len(zombies)
col = len(zombies[0])
count = 0
if row == 0 or col == 0:
return count
visited = [[False for j in range(col)] for i in range(row)]
for i in range(row):
bol = False
for j in range(row):
if zombies[i][j] == '1' and visited[i][j] == False and visited[j][i] == False:
visited[i][j] = True
visited[j][i] = True
DFS(j, visited, zombies, row)
if bol == 0:
count += 1
bol = True
return count
if __name__ == '__main__':
# array input of zombie
zombie_array = list()
zombie_count = int(input())
for i in range(int(zombie_count)):
n = raw_input()
zombie_array.append(str(n))
# zombie_array = ["1100" ,"1110", "0110", "0001"]
# print out the result
print(zombieCluster(zombie_array))我正在为以下代码编写测试代码(test_q4.py):
# -*- coding: utf-8 -*-
import unittest
import os
import sys
BASEDIR = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
sys.path.insert(0, BASEDIR)
from q4 import zombieCluster
class Test(unittest.TestCase):
def testzombieCluster(self):
zombie_array = ["1100", "1110", "0110", "0001"]
expect = 2
result = zombieCluster(zombie_array)
self.assertEqual(result, expect)
if __name__ == '__main__':
unittest.main()但是,当我从控制台运行这个命令python test_q4.py时,它会产生一个错误:
Traceback (most recent call last):
File "test_q4.py", line 9, in <module>
from q4 import zombieCluster
File "/home/rowle/Desktop/python/solution/q4.py", line 42, in <module>
print(zombieCluster(zombie_array))
NameError: name 'zombie_array' is not defined当我从源代码中删除print(zombieCluster(zombie_array))时,我的测试运行良好,但是如果删除这一行,我将看不到任何输出。
在这种情况下,我应该在测试代码中做什么?此外,如何测试源代码的主函数?
发布于 2018-04-26 02:04:07
创建一个()并将代码如下所示:
def main():
# array input of zombie
zombie_array = list()
zombie_count = int(input())
for i in range(int(zombie_count)):
n = raw_input()
zombie_array.append(str(n))
# zombie_array = ["1100" ,"1110", "0110", "0001"]
# print out the result
print(zombieCluster(zombie_array))
if __name__ == '__main__':
main()https://stackoverflow.com/questions/50033692
复制相似问题