Dominik Kaeufer
Dominik Kaeufer

Reputation: 63

Building own Graph in Python with Dictionary

i tried to build own graph in python. Dictionaries are perfect for this but i think iam to stupid to use them.

def add_edge(gra, edge):

        edge = set(edge)
        vertex1 = edge.pop()
        if edge:

            vertex2 = edge.pop()
        else:

            vertex2 = vertex1
        if vertex1 in gra:
            gra[vertex1].append(vertex2)
        else:
            gra[vertex1] = [vertex2]

i tried this to add some edges to the graph. When i use this:

z = {0:[],1:[],2:[],3:[],4:[],5:[]}

for i in range(0,6):
    add_edge(z,(i,50))
print(z)

i would except that it would add:

{0:[50],1:[50],2:[50],3:[50],4:[50],5:[50]}

but i get:

{0: [50], 1: [50], 2: [50], 3: [], 4: [], 5: [], 50: [3, 4, 5]}

what is wrong with my idea?

Upvotes: 1

Views: 89

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476567

For "older" Python implementations, a set is an unordered datastructure (well from it uses insertion order).

This means that if you add an element to a set, by .pop() you can retrieve the elements in any order. So here you insert for example (1, 50), but you retrieve it back as 50 and 1.

But you do not need a set anyway, you can just "unpack" your tuple:

def add_edge(gra, edge):
    vertex1, vertex2 = edge
    if vertex1 in gra:
        gra[vertex1].append(vertex2)
    else:
        gra[vertex1] = [vertex2]

or in case your tuple can contain more elements, we can use for example islice(..) here:

from itertools import islice

def add_edge(gra, edge):
    vertex1, vertex2 = islice(edge, 2)
    if vertex1 in gra:
        gra[vertex1].append(vertex2)
    else:
        gra[vertex1] = [vertex2]

By iterating, we can also take all sorts of collections (that are not per se subscriptable).

Upvotes: 2

Related Questions