Ryan
Ryan

Reputation: 1432

Code to make complete graph fails unit test, yet produces correct answer

The following code produces this error during unit testing at the line marked with a comment: (Exception: TypeError) "'int' object is not iterable"

The visual debugger detects no errors and produces the desired output. That is, make_complete_graph(2) yields the graph {0: set([1]), 1: set([0])}.

The graph representation is non-negotiable.

The error occurs on the highlighted line. The permutations routine is included in the original file, as the unit tester has issues importing itertools. However, I have substituted itertools for brevity here. Any thoughts on why this is happening would be appreciated.

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([])}

Upvotes: 0

Views: 29

Answers (1)

ducminh
ducminh

Reputation: 1352

To add e[1] to the set new_dict[n], use

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

instead of

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

set() creates a set from an iterable, while e[1] is an integer, not an iterable.

Upvotes: 2

Related Questions