jlsr10
jlsr10

Reputation: 33

Python - Adding values to a set that is not equal to the dictionary key

I have a function to make a complete graph. It takes an input that is an integer, n. The function is meant to return a dictionary, where keys are the nodes (0 to n-1), and values are sets with numbers that do not include the node. My function is currently this:

def make_complete_graph(num_nodes):

    new_dict = {}
    new_set = set([])

    for i in range(0, num_nodes):
        new_dict[i] = new_set


    for key, value in new_dict.items():
        for j in range(0, num_nodes):
            if j != key:
                value.add(j)

    return new_dict

but it returns:

{0: {0, 1, 2, 3, 4}, 1: {0, 1, 2, 3, 4}, 2: {0, 1, 2, 3, 4}, 3: {0, 1, 2, 3, 4}, 4: {0, 1, 2, 3, 4}}

when I want it to return

{0: {1, 2, 3, 4}, 1: {0, 2, 3, 4}, 2: {0, 1, 3, 4}, 3: {0, 1, 2, 4}, 4: {0, 1, 2, 3}}

It seems to ignore the if j != key line. How do I go about resolving this?

Upvotes: 0

Views: 116

Answers (2)

khelwood
khelwood

Reputation: 59113

You used the same set (new_set) as every value.

If you change

new_dict[i] = new_set

to

new_dict[i] = set()

then you'd have a different set at each value, and those sets can be updated independently.

Alternatively, you could simplify your whole code using comprehensions:

def make_complete_graph(num_nodes):
    return {key:{n for n in range(num_nodes) if n!=key} for key in range(num_nodes)}

Upvotes: 1

Gabio
Gabio

Reputation: 9494

The problem that you use the same set for every value in your dictionary and all add operations are performed on the same set. The result is that all the values of your dict are equal to the set you declared with all the modifications that you made for it.

As a side note, you can accomplish your task without the first loop:

def make_complete_graph(num_nodes):
    new_dict = {}
    for i in range(num_nodes):
        new_dict[i] = set(filter(lambda x: x!=i, range(num_nodes)))
    return new_dict

print(make_complete_graph(5))
# output: {0: {1, 2, 3, 4}, 1: {0, 2, 3, 4}, 2: {0, 1, 3, 4}, 3: {0, 1, 2, 4}, 4: {0, 1, 2, 3}}

Upvotes: 0

Related Questions