制作完整图表的代码无法进行单元测试,但会生成正确答案

时间:2018-04-08 12:58:09

标签: python python-2.7 graph

以下代码在标记为注释的行的单元测试期间产生此错误: (Exception: TypeError) "'int' object is not iterable"

可视化调试器检测到没有错误并产生所需的输出。也就是说,make_complete_graph(2)产生图{0:set([1]),1:set([0])}。

图表表示是不可协商的。

突出显示的行发生错误。排列例程包含在原始文件中,因为单元测试器在导入itertools时遇到问题。但是,为了简洁,我在这里替换了itertools。任何关于为什么会发生这种情况的想法将不胜感激。

from itertools import permutations

def make_complete_graph(num_nodes):
    '''
    Input: Number of nodes (an int) in graph.
    Output: Complete directed graph containing all possible edges subject to restriction
    that self-loops are disallowed & number of nodes must be positive. If number of nodes is
    not positive, empty graph is returned. 
    '''
    if num_nodes > 0:
        new_dict = {}
        nodes = [i for i in range(0, num_nodes)]
        edges = list(permutations(nodes, r=2))
        for n in nodes:
            new_dict[n] = set()
            for e in edges:
                if n == e[0]:
                    # the error occurs at this line
                    new_dict[n].add(set(e[1]))
        return new_dict
    else:
        return {num_nodes: set([])}

1 个答案:

答案 0 :(得分:2)

要将e[1]添加到集new_dict[n],请使用

new_dict[n].add(e[1])

而不是

new_dict[n].add(set(e[1]))

set()从可迭代创建一个集合,而e[1]是一个整数,而不是可迭代的。