Thursday, March 10, 2011

Eulerian Path - Python Code

Hello to all my followers... zero.  I am back. Today I am going to post some python code that finds an Eulerian path in a directed graph. If all nodes in the graph have the same in-degree as out-degree we can pick any start node an it will find an Eulerian cycle. If not all nodes have the same in-degree as out-degree then we can find an Eulerian path if only two vertices don't have the same in-degree as out-degree,
one of them has out-degree = in-degree + 1
and the other has in-degree = out-degree + 1
Then you can start at the first vertex of these two and find an Eulerian path that ends in the other vertex.

-------------------------------------------------------

def printTableu(tableu):
print '----------------------'
for row in tableu:
print row
print '----------------------'
return

G = [ [],
[2,6,8,9],
[1,3,4,8],
[2,4],
[2,3],
[7,8],
[1,9],
[5,8],
[1,2,5,7],
[1,6]]


printTableu(G)


def Euler (G, location):
stack = []
path = []
while (len(stack) > 0) or (len(G[location]) > 0):
if (len(G[location]) > 0):
stack.append(location)
location = G[location].pop(0)
elif (len(stack) > 0):
path.append(location)
location = stack.pop()
path.append(location)
return path


circuit = Euler(G, 1)
print circuit

-------------------------------------------------------

good to go.

MArio

No comments:

Post a Comment