Pooja Gupta
Pooja Gupta

Reputation: 357

Implementing Graph using Python

I am new to python and trying to implement graph data structure in Python. I have written this code, but i am not getting the desired result i want. Code:

class NODE:
    def __init__(self):
        self.distance=0
        self.colournode="White"

adjlist={}

def addno(A,B):
    global adjlist
    adjlist[A]=B

S=NODE()
R=NODE()
V=NODE()
W=NODE()
T=NODE()
X=NODE()
U=NODE()
Y=NODE()

addno(S,R)

for keys in adjlist:
    print keys

I want the code to print {'S':R} on the final line but it is printing this:

<__main__.NODE instance at 0x00000000029E6888>

Can anybody guide me what am i doing wrong? Also what to do if i want to add another function call like addnode(S,E) and printing should be {S:[R,E]}

Upvotes: 0

Views: 94

Answers (2)

martin.macko.47
martin.macko.47

Reputation: 897

You node needs to have a label to print. You can't use just the variable name. The node has no way knowing name of your variable.

class NODE:
    def __init__(self, name):
        self.name=name
    def __repr__(self):
        return self.name

adjlist={}
def addno(A,B):
    global adjlist
    adjlist[A]=B

S=NODE('S')
R=NODE('R')
addno(S,R)

print adjlist    
>>> {S: R}

However python dict may have only one value for each key, so you wont be able to save {S: R} and {S: V} at the same time. Instead you will need to save aj array of nodes:

class NODE:
    def __init__(self, name):
        self.name=name
    def __repr__(self):
        return self.name

adjlist={}
def addno(A,B):
    global adjlist
    if A not in adjlist:
        adjlist[A] = []
    adjlist[A].append(B)

S=NODE('S')
R=NODE('R')
V=NODE('V')
W=NODE('W')
addno(S,R)
addno(S,V)
addno(R,W)

print adjlist
{S: [R, V], R: [W]}

As a side note, using unnessesary global variables is a bad habit. Instead make a class for the graph:

class Node:
    def __init__(self, name):
        self.name=name
    def __repr__(self):
        return self.name

class Graph:
    def __init__(self):
        self.adjlist={}
    def addno(self, a, b):
        if a not in self.adjlist:
            self.adjlist[a] = []
        self.adjlist[a].append(b)
    def __repr__(self):
        return str(self.adjlist)

G=Graph()
S=Node('S')
R=Node('R')
V=Node('V')
W=Node('W')
G.addno(S,R)
G.addno(S,V)
G.addno(R,W)

print G
>>> {R: [W], S: [R, V]}

Upvotes: 2

anekix
anekix

Reputation: 2563

You get that output because Node is an instance of a class ( you get that hint form the output of your program itself see this: <main.NODE instance at 0x00000000029E6888> ).

i think you are trying to implement adjacency list for some graph algorithm. in those cases you will mostly need the color and ``distanceto othernodes`. which you can get by doing :

for keys in adjlist:
    print keys.colournode , keys.distance

Upvotes: 0

Related Questions