代码之家  ›  专栏  ›  技术社区  ›  Ryan

生成完整图形的代码未通过单元测试,但生成正确答案

  •  0
  • Ryan  · 技术社区  · 8 年前

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

    可视化调试器不会检测到任何错误并生成所需的输出。也就是说,make\u complete\u 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 回复  |  直到 8 年前
        1
  •  2
  •   ducminh    8 年前

    添加 e[1] 到集合 new_dict[n] 使用

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

    而不是

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

    set() 从iterable创建集合,而 e【1】 是整数,而不是iterable。